I have the following code:
class Pet {
public:
virtual string speak() const { return ""; }
};
class Dog : public Pet {
public:
string speak() const { return "Bark!"; }
};
int main() {
Dog ralph;
Pet* p1 = &ralph;
Pet& p2 = ralph;
Pet p3;
// Late binding for both:
cout << "p1->speak() = " << p1->speak() <<endl;
cout << "p2.speak() = " << p2.speak() << endl;
// Early binding (probably):
cout << "p3.speak() = " << p3.speak() << endl;
}
I have been asked to determine whether the compiler uses early or late binding for the final function call. I have searched online but have found nothing to help me. Can someone tell me how I would carry out this task?
Early binding reduces the number and severity of run-time errors because it allows the compiler to report errors when a program is compiled. Late binding can only be used to access type members that are declared as Public . Accessing members declared as Friend or Protected Friend results in a run-time error.
Using a Virtual Function In C++, late binding is achieved by inserting a virtual keyword preceding the declaration of the function in the base class. This informs the compiler that this function is designated for late binding.
Virtual Function is a member function of the base class which is overridden in the derived class. The compiler performs late binding on this function. To make a function virtual, we write the keyword virtual before the function definition.
By default, C++ matches a function call with the correct function definition at compile time. This is called static binding.
You can look at the disassembly, to see whether it appears to be redirecting through a vtable.
The clue is whether it calls directly to the address of the function (early binding) or calls a computed address (late binding). The other possibility is that the function is inlined, which you can consider to be early binding.
Of course the standard doesn't dictate the implementation details, there may be other possibilities, but that covers "normal" implementations.
You can always use hack :D
//...
Pet p3;
memset(&p3, 0, sizeof(p3));
//...
If compiler does use vtbl pointer, guess what will gonna happen :>
p3.speak() // here
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