c++ - Need work around for limitation: abstract class cannot be used for return types -
i have c++ class implementation wish hide using pimpl pointer. of work done, , everything's ok except operator '+=' returns object of same class. operator function required in class. problem when made abstract class, no member functions can return object of class, '+=' isn't allowed.
i asking advice on dealing limitation. i'd prefer way doesn't require changing existing code uses class. if way doesn't exist, else can done?
here's simplified version of class wish make abstract:
class aclass { public: aclass( int x0, int y0); ~aclass(void); void operator=(const aclass &a2); aclass operator+(const aclass &a2); void operator+=(const aclass &a2); protected; int x; int y; }; aclass aclass::operator+(const aclass &a2) { aclass aout(a2); aout += a2; return aout; } aclass aclass::operator+=(const aclass &a2) { this->x += a2.x; this->y += a2.y; } // 'operator+' necessary perform following operation on aclass objects. i.e. = b + c; // 'operator+=' necessary perform following operation on aclass objects. i.e. += b;
except operator '+=' returns object of same class
operator+=
(as other assignment operators) need return aclass&
instead of aclass
.
see e.g. scott meyers "effective c++" item 10:
have assignment operators return reference
*this
this way avoid problem of returning class value, , make code closer c++ guidelines.
p.s. operator+=
not seem point. instance, operator+
has same issue, , should not return reference. may consider post literal answer question, not solution problem.
Comments
Post a Comment