Thursday, January 31, 2008

Object slicing

look at the former post for slicing.

what happens when the virtual function is called?When passing by value, the copy-constructor for a BASE object is used, which initializes the VPTR to the BASE VTABLE and copies only the BASE parts of the object. There’s no explicit copy-constructor here, so the compiler synthesizes one. Under all interpretations, the object truly becomes a BASE during slicing.

upcasting into an object is not done often; in fact, it’s usually something to watch out for and prevent.

if the function in the base class was made into a pure virtual function, then the compiler would prevent object slicing because that wouldn’t allow you to “create” an object of the base type (which is what happens when you upcast by value). This could be the most important value of pure virtual functions: to prevent object slicing by generating a compile-time error message if someone tries to do it.

No comments:

Post a Comment