What is binding in C++?
In C++, binding refers to the association between a function call and the corresponding function definition or object during program execution. There are two main types of binding in C++: static binding and dynamic binding.
1. Static Binding (Early Binding)
Static binding occurs at compile time. The compiler determines the method to call based on the type of the reference or pointer used. This is the default behavior for non-virtual functions and function overloading.
- Example:
class Base { public: void show() { cout << "Base class show function called." << endl; } }; class Derived : public Base { public: void show() { cout << "Derived class show function called." << endl; } }; int main() { Base b; Derived d; Base* ptr = &d; // Base class pointer to derived class object ptr->show(); // Calls Base class show function (static binding) return 0; }
In this example, the call to show()
is bound to the Base
class version at compile time, resulting in the output from the base class even though ptr
points to a derived class object.
2. Dynamic Binding (Late Binding)
Dynamic binding occurs at runtime and is associated with virtual functions. When a function is declared as virtual
in the base class, C++ uses the actual object type to determine which function to call at runtime, allowing for polymorphic behavior.
- Example:
class Base { public: virtual void show() { // Declare show() as virtual cout << "Base class show function called." << endl; } }; class Derived : public Base { public: void show() override { cout << "Derived class show function called." << endl; } }; int main() { Base* ptr = new Derived(); // Base class pointer to derived class object ptr->show(); // Calls Derived class show function (dynamic binding) delete ptr; // Clean up memory return 0; }
In this case, the show()
function is determined at runtime, and the output will be from the Derived
class, demonstrating dynamic binding.
Conclusion
Binding is a crucial concept in C++ that influences how function calls are resolved. Static binding is efficient and occurs at compile time, while dynamic binding allows for more flexible and polymorphic designs by resolving function calls at runtime.
Sources:
GET YOUR FREE
Coding Questions Catalog