Re: vtable on stack

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

 



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@xxxxxxxxxx
Check us out at www.digium.com & www.asterisk.org

[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