title: Calling a virtual function using an object created on stack
body: <p>I don't have much experience or knowledge of virtual functions, so the question may have an obvious answer. I am just trying to understand the reasoning.</p>
  <p>I have a simple CTest class with two functions- <code>func()</code> and <code>virtualFunc()</code>. I am creating an object on the stack purely for testing purposes and want to observe its behaviour. I do realize we are supposed to create an object using <code>new</code> keyword on the heap, but I am interested in knowing the behaviour of a virtual function when the object is on the stack.</p>
  <p>With the code that I have currently, it is resulting in a Seg Fault when I try to call the virtual function. Can anyone tell me why does virtual function result in a seg fault while the non-virtual function doesn't?</p>
  <pre><code>class CTest {
      public:
          void func() {
              printf(&quot;function was called.\n&quot;);
          }   
          virtual void virtualFunc() {
              printf(&quot;virtual function was called.\n&quot;);
          }   
  };
  
  int main (int argc, char ** argv) {
      CTest * obj = NULL;
      
      obj-&gt;func(); // this would print &quot;function called&quot; as what's inside the func()
      
      obj-&gt;virtualFunc(); 
      //line above results in segfault because C *obj is on stack; 
      //You would need to allocated obj on the heap for the virtual function to not Seg Fault.WHY?
      //by using &quot;C*obj = new C&quot;, I am able to print the contents of virtualFunc() successfully.
  
  }
  </code></pre>