Computer Science Canada Type Slicing Fun |
Author: | Geminias [ Fri May 23, 2008 8:34 pm ] | ||
Post subject: | Type Slicing Fun | ||
Explain the cause for the two different outputs:
|
Author: | md [ Fri May 23, 2008 10:25 pm ] |
Post subject: | RE:Type Slicing Fun |
Are you asking for help? An explanation? Or simply pointing out how nifty virtual functions are? /me is a bit confused |
Author: | Geminias [ Sat May 24, 2008 1:18 am ] |
Post subject: | RE:Type Slicing Fun |
The second one: an explanation. (Not the top level but the underlying mechanics of the vtable and RTTI that causes the discrepancy.) |
Author: | md [ Mon May 26, 2008 9:13 am ] |
Post subject: | RE:Type Slicing Fun |
When the compiler sees your definition of Base it finds virtual functions. It then adds a vtable structure to the class, which contains function names (sorta...) and the address of the function. When you derive something from a class with virtual functions the compiler copies the vtable structure from the base class, and then changes any function pointers in the new vtable that the derived class overwrote. When you call virtual functions, the compiler inserts code to read the vtable of the object, and then call the function pointed to. Objects of the derived class have a a different vtable - and thus a different function call. In your example you have two vectors, one of Base, the other of Base*. When you add things to the first vector it's actually making copy (derived is cast into base, then copied) and the new copy's vtable is copied from Base. In the second your just using pointers and there is no creation of new objects. |
Author: | wtd [ Wed May 28, 2008 12:32 pm ] |
Post subject: | RE:Type Slicing Fun |
Virtual functions: the way OOP is really supposed to work. |