Emerson Xu Emerson Xu - 2 months ago 8
C++ Question

Quickly assign all the members of a base object to a derived object in C++

Say we have one base class and one derived class:

class Base {
string s1;
string s2;
...
string s100; // Hundreds of members
};

class Derived : public Base{
string s101;
};


I want to assign a Base object
base
to a Derived object
derived
. I know we can't just use operator "=" to assign a base object to its derived object.
My question is: Do we have to make copies of all the members one by one? Like:

derived.s1 = base.s1;
derived.s2 = base.s2;
...
derived.s100 = base.s100;


Is there any faster or more concise way to do this? Overload an operator= with
the returned base object?

Answer

I want to assign a Base object base to a Derived object derived.

Provide an overload operator= for it:

class Derived : public Base {
    Derived& operator=(const Base& b) { 
        Base::operator=(b); // call operator= of Base
        s101 = something;   // set sth to s101 if necessary
        return *this; 
    }
};

Then you can

Base b;
// ...
Derived d;
// ...
d = b;