All Courses
OOP: POLYMORPHISM

Dynamic Binding

Binding means connecting a function call to the actual function body that will run.

There are two important types:

  • Static binding.
  • Dynamic binding.

Static Binding

Static binding happens at compile time.

Example:

calculator.add(2, 3);

The compiler knows exactly which add() function to call.

Dynamic Binding

Dynamic binding happens at runtime.

It is used with virtual functions.

basePointer->show();

The program checks the actual object type and calls the correct overridden function.

Complete Example

#include <iostream>
using namespace std;

class Notification {
public:
    virtual ~Notification() = default;

    virtual void send() const {
        cout << "Sending notification" << endl;
    }
};

class EmailNotification : public Notification {
public:
    void send() const override {
        cout << "Sending email" << endl;
    }
};

class SmsNotification : public Notification {
public:
    void send() const override {
        cout << "Sending SMS" << endl;
    }
};

void deliver(const Notification& notification) {
    notification.send();
}

int main() {
    EmailNotification email;
    SmsNotification sms;

    deliver(email);
    deliver(sms);

    return 0;
}

Output:

Sending email
Sending SMS

V-Table Basic Idea

C++ usually implements dynamic binding using:

  • V-table: a hidden table of virtual function addresses.
  • V-pointer: a hidden pointer inside the object that points to the correct table.

You do not manually use these. They are compiler implementation details.

For viva, the simple answer is enough:

Virtual function calls through base pointers or references are resolved at runtime using the actual object type.

Viva Answer

Dynamic binding means a function call is connected to the correct function body at runtime. In C++, it happens through virtual functions when called using base-class pointers or references.

Quick Check

  1. What does binding mean?
  2. Is function overloading static or dynamic binding?
  3. What makes deliver(email) call EmailNotification::send()?