Dynamic binding in C++
Dynamic binding (also known as late binding or runtime binding) in C++ is a feature that allows the selection of the appropriate member function or method to be determined at runtime rather than at compile time. Dynamic binding is a fundamental concept in object-oriented programming and enables polymorphism, which is one of the pillars of OOP.
Dynamic binding is achieved in C++ through the use of virtual functions and inheritance. Here’s how it works:
- Virtual Functions: In C++, a virtual function is a member function of a base class that is declared with the
virtual
keyword. Subclasses (derived classes) can override these virtual functions to provide their own implementations. The choice of which function to call is determined at runtime based on the actual type of the object, rather than the declared type of the reference or pointer to the object.
class Base {
public:
virtual void print() {
std::cout << "Base class" << std::endl;
}
};
class Derived : public Base {
public:
void print() override {
std::cout << "Derived class" << std::endl;
}
};
- Polymorphism: With dynamic binding and virtual functions, you can create an array or collection of objects of different derived classes but treat them uniformly using a pointer or reference to the base class. When you call a virtual function through such a pointer or reference, the appropriate derived class’s implementation is executed:
int main() {
Base* obj1 = new Base();
Base* obj2 = new Derived();
obj1->print(); // Calls Base::print()
obj2->print(); // Calls Derived::print()
delete obj1;
delete obj2;
return 0;
}
In this example, obj2
is a pointer to a Derived
object, but when print()
is called on it, it calls the Derived
class’s implementation due to dynamic binding.
Dynamic binding is essential for achieving polymorphism and code extensibility in C++. It allows you to write code that can work with objects of different derived classes in a uniform way, and it’s a key concept in building flexible and maintainable object-oriented software.