Middle
What is early and late binding?
sobes.tech AI
Answer from AI
Early and late binding are concepts related to when exactly in the execution process it is determined which method or function will be called.
-
Early binding occurs at compile time. The compiler knows the exact address of the called function or method, which allows for optimization of calls. This typically involves static methods or functions without polymorphism.
-
Late binding occurs during program execution. It is characteristic of polymorphism and dynamic binding, where the specific method is chosen depending on the object type at the moment of the call. For example, virtual functions in C++.
Example in C++:
class Base {
public:
virtual void foo() { std::cout << "Base" << std::endl; }
};
class Derived : public Base {
public:
void foo() override { std::cout << "Derived" << std::endl; }
};
Base* b = new Derived();
b->foo(); // the call is made through late binding, output: Derived
Here, the call to foo() is determined at runtime, which allows for polymorphism.