Lakash Dangol
Lakash Dangol

Reputation: 51

can dynamic binding happen without using pointer and using regular object in 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 ?

Upvotes: 4

Views: 844

Answers (1)

user12002570
user12002570

Reputation: 1

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
    
}

Upvotes: 3

Related Questions