vtable on stack

Frank Winter frank.winter@desy.de
Tue Feb 2 12:45:00 GMT 2010


Dear Eljay,

thank you for your reply!

>
> To fix your example, do this:
>   B y = B();

You are right. This creates a B on the stack and B::f() gets called.
Nevertheless, here virtual functions are not involved. The vtable is not 
used when calling y.f()

My example created an A on the stack, and assigned a B to it, without 
turning the A into a B. Right!

But, I wanted to use virtual functions with class objects purley living 
on the stack _without_ doing some sort of casting:

B y = B();
dynamic_cast<A*>(&y)->f(); // B::f() called
(*(A*)(&y)).f();           // B::f() called

Nobody would want to write this. But somebody might want to use 
objects with virtual functions and define hers object on the stack, like:

vector<A> ve;
ve.push_back(A());
ve.push_back(B());
ve.push_back(A());

iterate over it and call ::f(). Then always A::f() gets called, because 
its a vector of A. But a B is also an A. Thatfor I can insert it into the 
vector.

This example can only be realized with

vector<A*>.

I think, its not possible to make use of the vtable with objects 
living on the stack.

--
Frank




More information about the Gcc-help mailing list