What is dynamic Binding in C++?

what is an easy example to learn dynamic binding in C++.

During dynamic binding, the compiler determines the appropriate function call for an object at runtime.
For instance, as the CTO of your company, you may want to distribute annual increments and bonuses to your employees.
Here is an example how you can do using C++.

#include <bits/stdc++.h>
using namespace std;


class Employee {
    public:
        virtual void annualIncrement() = 0;
        virtual int getSalary() = 0;
};

class SDE: public Employee {
    int salary = 1000;
    int incrementPercent = 10;
    
    public:
        void annualIncrement() {
            this->salary = this->salary * (100 + this->incrementPercent) / 100 + 500;
        }
        int getSalary() {
            return this->salary;
        }
};

class PM: public Employee {
    int salary = 1100;
    int incrementPercent = 15;
    public:
        void annualIncrement() {
            this->salary = this->salary * (100 + this->incrementPercent) / 100 + 600;
        }
        int getSalary() {
            return this->salary;
        }
};


int main() {
	
	Employee *E[2] = {new SDE(), new PM()};
	
	for(int i=0;i<2;i++) {
	    E[i]->annualIncrement();
	    cout<<E[i]->getSalary()<<endl;
	}
	
	return 0;
}

Suppose you have an Employee class with two virtual functions, each implemented in the class that extends it. To distribute increments and bonuses, you create two objects - one for an SDE and another for a PM - and increment their salaries. Since both the SDE and PM classes have their own implementation of the annualIncrement function, the appropriate function call will be determined during runtime.

You may run the code yourself using this link and check the output.

1 Like