c++ - avoiding duplication in the assignment operator of a derived class -
consider assignment operators in classes parent
, 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;// line return *this; }; void setc(double inc){mc = inc;}; double getc(){return mc;}; protected: double mc; };
is here way avoid duplicate line mp = other.mp;
?
the reason asking number of bases higher , inheritance structure gets more complicated, easy lose track of members.
edit
the reason need implement operator=
needs check things before assignments.
just call parent operator:
child& operator=(const child& other) { mc = other.mc; parent::operator=(other); return *this; }
or really, don't implement either operator since both trivial!
Comments
Post a Comment