Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Derived class inherit base class assignment operator?

It seems to me that Derived class don't inherit base class Assignment operator
if Derived class inherit Base class assignment operator , can you please explain the following example

In the following code I am overriding base class operator= in Derived, so that Derived class default assignment operator calls overloaded operator=

#include <iostream>  
using namespace std;      
class Base  
{  
    public:  
    Base(int lx = 0):x(lx)  
    {  
    }  

    virtual Base& operator=( const Base &rhs)  
    {  
        cout << "calling Assignment operator in Base" << endl;  
        return *this;  
    }

    private:  
    int x;     
};      


class Derived : public Base  
{  
    public:  
    Derived(int lx, int ly): Base(lx),y(ly)  
    {  
    }

    Base& operator=(const Base &rhs)  
    {  
        cout << "Assignment operator in Derived"<< endl;  
        return *this;  
    }  

    private:  
    int y;    
};  



int main()  
{  
    Derived d1(10,20);  
    Derived d2(30,40);  
    d1 = d2;  
}  

It gives the output

calling Assignment operator in Base

I have re-written base class operator= into derived class, so if derived class inherits base class operator= then it should be get overridden by operator= (that i have written in derived class), and now Derived class default operator= should call overridden version and not from the base class operator=.

like image 281
Amit Avatar asked Feb 04 '26 04:02

Amit


1 Answers

The compiler generates a default assignment operator for Derived (which hides the operator of Base). However, the default assignment operator calls all assignment operators of the class' members and base classes.

like image 61
Bo Persson Avatar answered Feb 05 '26 21:02

Bo Persson



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!