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:
#include <iostream>
using namespace std;
struct hello {
virtual void say() { cout << "hello" << endl; }
};
struct world : public hello {
virtual void say() { cout << "world" << endl; }
};
void force(hello h) {
h.say();
}
int main() {
world w;
w.say();
force(w);
return 0;
}
This code outputs (link to ideone)
world
hello
even though you'd expect an object of type world to "say" world, not hello. C++ compiler is smart in noticing that w is passed to hello by value, so it adjusts the vtable to avoid calls of methods in the derived class.
world world? You are allowed to insert a single character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With