简体   繁体   中英

What is the right way to overload the assignment operator for a derived class?

Let's say I have a Base class:

class Base
{   
    public:
        Base(float x, float y, float z, float w): 
                    x(x), y(y), z(z), w(w) {}
        float x;
        float y;
        float z;
        float w;
};
bool operator==(const Base &a, const Base &b);

Now, I have a Derived class from Base :

class Derived: public Base {
    public:
        Derived(float x, float y, float z)
            : Base(x, y, z, 0)
            , r(x), g(y), b(z)
            {};
        float r;
        float g;
        float b;
};

Now, suppose I want to write an overloaded assignment operator for my Derived class. Currently, this is what my code looks like:

Derived& Derived::operator=(const Derived &a){
    x = a.r;
    y = a.g;
    z = a.b;
    
    r = a.r;
    g = a.g;
    b = a.b;

    return *this;
}

I need to assign the x , y and z members of the Base class as above, because the == operator for my Derived class is the overloaded == operator of the Base class, which uses those members. Consider this snippet, for instance (assuming x , y and z weren't assigned in the overloaded assignment operator):

Derived a = Derived(1,2,3);
Derived b = Derived(1,2,3);

bool val = (a == b); // true!

b = Derived(4,5,6);

bool val = (a == b); // still true because b.x, b.y and b.z haven't changed!

I feel like I'm doing this the wrong way; shouldn't assignment of a derived class be concerned with only the derived class members? But how do I make it compatible with the overloaded operators of the base class? Is there a better way to achieve what I'm doing?

Assuming you have an operator= in the Base class, you could write:

Derived& Derived::operator=(const Derived &a){
    
    Base::operator=(static_cast<Base const&>(a));    

    r = a.r;
    g = a.g;
    b = a.b;

    return *this;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM