vtable on stack

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Do virtual functions work with class objects created on the stack?
Consider the example below.

First the class object is created on the heap and the f() call binding
is done via vtable as supposed.

Second, the class lives on the stack. B is created, assignment operator to A called. But the f() call prints "class A". Maybe here the vtable is not copied..?

I used structs here to avoid con/destructor calls.

How would one use virtual functions with objects living on the stack. Is it possible at all?

--
Frank



#include <iostream>
using namespace std;

struct A {
   virtual void f() { cout << "Class A" << endl; }
};

struct B: A {
   void f() { cout << "Class B" << endl; }
};


int main() {
  A* x = new B();
  x->f();         // Class B

  A y = B();
  y.f();          // Class A
}




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux