Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can dynamic binding happen without using pointer and using regular object in c++

Tags:

c++

#include<iostream>
using namespace std;
class Base{
    public:
    virtual void fun(){
        cout<<"Base"<<endl;
    }
};
class Derived:public Base{
    public:
    virtual void fun(){
        cout<<"Derived"<<endl;
    }
};
int main(){
    Derived d1;

    d1.fun(); // which binding work here? static binding or dynamic binding
    return 0;
}

In the above code I just want to know which binding will work in d1.fun() and why that binding happens ?

like image 761
Lakash Dangol Avatar asked Sep 15 '25 03:09

Lakash Dangol


1 Answers

For the call expression d1.fun() to work using dynamic binding both of the below given conditions must be satisfied:

  1. The call should be made using a reference or a pointer to the Base class.
  2. The member function fun should be a virtual member function.

If any of the above 2 conditions is not met, then we will have static binding.

Since in your example, d1 is an ordinary(non-reference/ non-pointer) object, condition 1 is violated(not met), and so we have static binding.

int main(){
    
    Derived d1;
    Base *bPtr = &d1;
    
    bPtr->fun(); //dynamic binding 
    
    Base &bRef = d1;
    bRef.fun();  //dynamic binding 
    
    d1.fun();   //static binding
    
}
like image 146
Anoop Rana Avatar answered Sep 17 '25 19:09

Anoop Rana