c-plus-plus
  1. c-plus-plus-dynamic-binding

C++ Programs Dynamic Binding

Dynamic binding (also known as runtime polymorphism) is a feature in C++ that allows a function call to be resolved at runtime rather than at compile-time. This is achieved through the use of virtual functions and pointer references.

Syntax

class BaseClass {
public:
    virtual void virtualFunction() {
        // code
    }
};

class DerivedClass : public BaseClass {
public:
    void virtualFunction() override {
        // code
    }
};

int main() {
    BaseClass* ptr = new DerivedClass();
    ptr->virtualFunction();
    delete ptr;
    return 0;
}

In the above example, BaseClass is the base class and DerivedClass is derived from BaseClass. The virtual keyword is used to declare a virtual function in the BaseClass. The override keyword is used in the DerivedClass to indicate that it is overriding the virtual function.

Example

#include <iostream>
using namespace std;

class Shape {
public:
    virtual void draw() {
        cout << "Drawing Shape" << endl;
    }
};

class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing Circle" << endl;
    }
};

int main() {
    Shape* shapePtr = new Circle();
    shapePtr->draw();
    delete shapePtr;
    return 0;
}

Output

Drawing Circle

Explanation

In the above example, we have a base class called "Shape" with a virtual function called "draw". The "Circle" class is derived from "Shape" and overrides the "draw" function. We create a pointer to a "Shape" object and assign it to a "Circle" object. When the draw function is called on the pointer object, it resolves to the derived class function.

Use

Dynamic binding is useful when you have a base class and multiple derived classes, where each derived class has its own implementation of a certain function. By using dynamic binding, you can call the function on a pointer to the base class and have it resolved at runtime to the correct derived class implementation.

Important Points

  • Dynamic binding is achieved through the use of virtual functions and pointer references.
  • Dynamic binding allows the function call to be resolved at runtime rather than at compile-time.
  • When a virtual function is overridden in a derived class, it is denoted with the override keyword.
  • Virtual functions should have a virtual destructor to ensure proper memory management.

Summary

In summary, dynamic binding is a C++ feature that allows a function call to be resolved at runtime rather than at compile-time. It is achieved through the use of virtual functions and pointer references. Dynamic binding is useful when working with a base class and multiple derived classes, where each derived class has its own implementation of a certain function.

Published on: