vtable on stack

Kevin P. Fleming kpfleming@digium.com
Tue Feb 2 13:40:00 GMT 2010

Frank Winter wrote:

> 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.

That's not quite correct here; you are not inserting a B into the vector
at all. In the second call to push_back(), a temporary B object is
instantiated on the stack, and then A's copy constructor is called to
create an A from it in the space allocated inside the vector (then the
temporary B object is destroyed). The vector does *not* contain a B
object at any time. As has previously been mentioned, the only way to
use polymorphism with objects in containers is to use pointer-to-object
or reference-to-object semantics; if you use value semantics, then the
objects will be sliced to the type that the container is defined to hold.

Kevin P. Fleming
Digium, Inc. | Director of Software Technologies
445 Jan Davis Drive NW - Huntsville, AL 35806 - USA
skype: kpfleming | jabber: kpfleming@digium.com
Check us out at www.digium.com & www.asterisk.org

More information about the Gcc-help mailing list