avoiding duplication in the assignment operator of a derived class

63 views Asked by At

Consider the assignment operators in classes Parent and Child, below.

#include <iostream>
class Parent 
{
public:
  Parent(){};
  virtual ~Parent(){};
  Parent& operator=(const Parent& other){mP = other.mP; return *this;};

  void setP(double inP){mP = inP;};
  double getP(){return mP;};
protected:
  double mP;
};


class Child : public virtual Parent
{
public:
  Child(){};
  virtual ~Child(){};
  Child& operator=(const Child& other)
  {
     mC = other.mC;
     mP = other.mP;// this line
     return *this;
  };

  void setC(double inC){mC = inC;};
  double getC(){return mC;};
protected:
  double mC;
};

Is here a way to avoid the duplicate line mP = other.mP;?

The reason I am asking is that as the number of bases get higher and the inheritance structure gets more complicated, it is easy to lose track of members.

EDIT

The reason I need to implement the operator= is that it needs to check some things before the assignments.

3

There are 3 answers

4
Barry On BEST ANSWER

Just call the Parent operator:

Child& operator=(const Child& other)
{
     mC = other.mC;
     Parent::operator=(other);
     return *this;
}

Or really, don't implement either operator since both are trivial!

0
A.S.H On
Child& operator=(const Child& other)   {
     mC = other.mC;
     mP = other.mP; 
}

you can invoke the assignment operator of the parent prior to the child specific assignment in this way:

 Child& operator=(const Child& other)
  {
     Parent::operator=(other);
     mC = other.mC;
     return *this;
  };
6
M.M On

The best way to avoid this issue is to remove both of your operator= functions.

The compiler-generated operator= applies operator= to each member variable and base class, which is just what you were trying to do anyway.

Re-implementing the wheel just makes your code harder to read and maintain -- and sometimes less efficient.