Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it called dynamic binding?

We use virtual to achieve dynamic binding in Cpp i.e. to decide at runtime which function has to be called based on the actual object created rather than the reference or the pointer variable.

class A
{
 int a;
public:
 virtual void show();
};

void A::show() { cout<<a<<endl; }

class B:public A
{
 int b;
public:
 void show() { cout<<b<<endl; }
};

class C:public A
{
 int c;
public:
 void show() { cout<<c<<endl; }
};

Assume, someFunction(A& aref). It can take an object of type B or C or A

Note: Assuming values of data members are set

I mean the path is defined (It can be A or B or C). It isn't exactly run time dependent [like asking user to enter age and the user enters some word or some other datatype].

But why is this called as run time binding? The compiler does make a check beforehand if the object to be assigned will be compatible or no.

Is the terminology used to indicate that there is no strict association of the reference variable with a particular type of object and it is decided at run-time. Is there more to this ?

like image 948
Suvarna Pattayil Avatar asked Dec 05 '25 10:12

Suvarna Pattayil


1 Answers

Virtual methods create a virtual table in the object which is used to call the methods.

The right method is looked up at runtime.

The case where it's most evident, is if you'd have a list of the base class, which contains different kinds of objects:

std::list<A*> myList = new std::list<A*>();
myList.push_back(new A());
myList.push_back(new B());
myList.push_back(new C());

for (A* a : myList)
{
    a->show();
}

In this little example all the objects are of different types, the compiler sees them all as A object (there's a variable of type A calling show()), but still the right method is called.

like image 89
Yochai Timmer Avatar answered Dec 06 '25 23:12

Yochai Timmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!