Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if a compiler uses early or late binding on a virtual function?

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?

like image 415
Bap Johnston Avatar asked Sep 30 '11 13:09

Bap Johnston


People also ask

How would you compare late binding and early binding?

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.

How late binding is achieved using virtual function?

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.

What is a virtual function explain early and 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.

Which type of binding is use in virtual function?

By default, C++ matches a function call with the correct function definition at compile time. This is called static binding.


2 Answers

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.

like image 192
Steve Jessop Avatar answered Sep 23 '22 23:09

Steve Jessop


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
like image 30
GreenScape Avatar answered Sep 20 '22 23:09

GreenScape