#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 ?
For the call expression d1.fun() to work using dynamic binding both of the below given conditions must be satisfied:
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
    
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With