Learning C++ with help of Bruce Eckel “Thinking in C++”. Stuck in exercise 30. Here it is:
If function calls to an object passed by value weren’t early-bound, a
virtual call might access parts that didn’t exist. Is this possible?
Write some code to force a virtual call, and see if this causes a
crash. To explain the behavior, examine what happens when you pass an
object by value.
I can understand result of calling virtual function for object, but I can not understand how to force compiler to do it, without proper constructors called.
Is there a way to treat one object as another without calling proper constructors or operators (for type conversion)?
Bruce is trying to illustrate object slicing, a situation when a polymorphic object is passed by value.
Here is how you can do it:
This code outputs (link to ideone)
even though you’d expect an object of type
worldto “say”world, nothello. C++ compiler is smart in noticing thatwis passed tohelloby value, so it adjusts the vtable to avoid calls of methods in the derived class.Bonus exercise to test if you understand passing by reference: can you modify my code so that it prints
worldworld? You are allowed to insert a single character.