Search code examples
c++inheritancedynamicvirtuallanguage-lawyer

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 ?


Solution

  • 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.