I just want to make sure I am understanding correctly. If a base class has a virtual function, every time an instance of the base class or a derived class gets created it as a vptr to the vtable. This is what enables polymorphism to work, but lets say I have a derived object and I copy it over to a base object, I understand that it would be sliced and I would lose access to the other parts of the derived object, but would it lose the vptr? or would i still be able to call the implementation of the derived class?
#Virtual methods and object slicing
28 messages · Page 1 of 1 (latest)
When your question is answered use !solved or the button below to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
There no longer would be an implementation of the derived class. It's a base, not a derived.
In practical terms, you could in theory call the derived function on a base anyway, but chances are it will try to access non-existent derived data members, so that's a bad idea.
wouldnt the vptr point to the vtable of the derived class?
or does it not work lioke that?
Also, a vtable is an implementation detail. No such thing needs to exist in the first place.
The vtable pointer would adjust to the base vtable.
What helps a bit are the terms "static type" and "dynamic type". In
Base &&b = Derived{};
b's static type is a Base, but its dynamic type is a Derived.
When you have Base b instead, both types are Base. The big feature of virtual is to call the function of the dynamic type.
In other words, polymorphism requires pointers or references. It's the only way for something to be one type but actually another type that still allows virtual functions to call the dynamic versions.
hm
im a little slow
but i think i understgand it slightly
so if I just do Base b then it's just a base object. Where as If i have Base *b it means that it points to a Base object and can safely access base object's memebers but also can "hold" derived classes
so when I invoke the members of the former example, it just calls the base implementation
Point to, not hold, but yes.
where as if i used the latter example it would look through the "vtable" first
Basically
Compilers are sometimes smart and simply ignore the vtable.
In the above example, a decent compiler would not consult the vtable, it simply sees that b is a Derived.
But that's an optimization detail. You can think of it as going through the vtable and that the vtable effectively stores the dynamic type.
okay
i see
so slicing just not only "deletes" the derived part it just absolutely is not recognized as a derived ever again
Right. Unless you copy or move it into a derived.
but then the new derived would be different since it's lost