Discuss the difference between early binding and late binding in the context of virtual functions and polymorphism. Provide an example illustrating both types of binding.
In the context of virtual functions and polymorphism, early binding and late binding refer to the timing at which the function call is connected to the function definition.
Early Binding:
Example of Early Binding:
#include <iostream> using namespace std; class Base { public: void display() { cout << "Display function of Base class" << endl; } }; class Derived : public Base { public: void display() { cout << "Display function of Derived class" << endl; } }; int main() { Base *basePtr; Derived derivedObj; basePtr = &derivedObj; // Base class pointer pointing to Derived class object basePtr->display(); // Early binding, calls Base class's display function return 0; }
In this example, the display
function is called using a pointer of the base class type that points to an object of the derived class. During early binding, the compiler resolves the function call to the base class's display
function based on the type of the pointer, not the actual object.
Late Binding:
Example of Late Binding:
#include <iostream> using namespace std; class Base { public: virtual void display() { cout << "Display function of Base class" << endl; } }; class Derived : public Base { public: void display() { cout << "Display function of Derived class" << endl; } }; int main() { Base *basePtr; Derived derivedObj; basePtr = &derivedObj; // Base class pointer pointing to Derived class object basePtr->display(); // Late binding, calls Derived class's display function return 0; }
In this example, the display
function is called using a pointer of the base class type that points to an object of the derived class. During late binding, the decision about which display
function to call is made at runtime based on the actual type of the object, resulting in the derived class's display
function being called.
I hope this clarifies the difference between early binding and late binding in the context of virtual functions and polymorphism.