title: So we can use virtual functions with objects allocated on stack?
body: <p>I thought for a long time that to use virtual functions, the class object has to be allocated with a pointer but I ran a test example and it seems it will perfectly work for objects on stack, it only depends on the syntax how you call it. But what I am doing feels almost like I am creating a 'cheat'to making the system do what I want, that is use a plain base class pointer to call a derived class virtual method.</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  using namespace std;
  
  class B{
  public:
      virtual void call() { cout&lt;&lt;"B\n"; };
  };
  
  class D: public B{
  public:
      void call()  {  cout&lt;&lt;"D\n"; }
  };
  
  int _tmain(int argc, _TCHAR* argv[])
  {
      B b;
      D d;
  
      b.call(); // output is "B"
  
      d.call(); // output is "D"
  
      B* obj = &amp;d;
      obj-&gt;call(); // output is "D"
  
      return 0;
  }
  </code></pre>
  
  <p>Is this acceptable to do in release software or will it raise eyebrows? I can use this to great advantage in my software but I haven't seen anything like this before.</p>
  
  <p>In my actual project, I have base and derived classes which are allocated on stack, lets call them <code>Base</code>, <code>DerivedA</code> and <code>DerivedB</code>. I want to restructure and add virtual functions to the base and I thought I will have to allocate them on heap now but looks like I don't have to. Now my application could be in certain state where all operations will be done on <code>DerivedA</code> or <code>DerivedB</code>so I plan to add a pointer object:</p>
  
  <pre><code>Base * obj = &amp;DerivedA;
  </code></pre>
  
  <p>Obviously when I need switch operations to other object, I just do <code>obj = &amp;DerivedB</code> and basically I will be using both objects indirectly through my new <code>obj</code>pointer for all operations. Does this look sound?</p>
  
  <p>Currently my code has <code>if else</code> statements to do operation either on <code>DerivedA</code> or <code>DerivedB</code>and this will eliminate those. </p>