C++ Derived Class assignment operator to base instance and vice versa

  assignment-operator, c++, inheritance

I have a class with some members (a,b,c) that I want to pass around and also some variables (d) that must not be moved around and instead stay with the instance.

class Base
{
 public:
     virtual ~Base()=default;
     double a;
     double b;
     double c;
}

class Derived : public Base
{
    double d;
}

I am happy with the compiler-generated assignment operator for each type with objects of the same type, including Derived1 = Derived2 (which I know will assign d from Derived2 to Derived1).

However, I now want to do the following Base_inst = Derived_inst and Derived_inst=Base_inst. In this case I want to copy the right-hand-sides (a,b,c) to the left-hand-side instance.

How should I achieve this?

My attempt is as follows:

class Derived;
class Base
{
public:
   Base& Base::operator=(Base const& other) = default;
   virtual Base& operator=(const Derived& other);
}

class Derived : public Base
{
    double d;
    Derived& Derived::operator=(Derived const& other) = default;
    virtual Derived& operator=(const Base& other);
}

and then implement each function by hand such that the members of other is assigned to the members of the caller lhs object. However, I have no idea what I am actually doing.

Source: Windows Questions C++

LEAVE A COMMENT