c++ - Assignment of base class object to derived class object -


why error: no match ‘operator=’ in ‘y = x’ in following code?
cant a-component of b not assigned a-object = a-object?

struct {int i;}; struct b : public {int j;};  int main() {     x;     b y;      x.i = 9;     y.j = 5;      y = x; // error: no match ‘operator=’ in ‘y = x’      // expected: y.i = 9      return 0; } 

you not explicitly defining assignment operators, compiler generate own default operators each struct. compiler's default assignment operator in b takes b input , assign both members. , assignment operators not automatically inherited when using inheritance. why cannot pass a b - there no assignment operator in b takes a input. if want allow that, need tell compiler much, eg:

struct {     int i;      a& operator=(const &rhs)     {         = rhs.i;         return *this;     } };  struct b : public {     int j;      using a::operator=;      b& operator=(const b &rhs)     {         *this = static_cast<const a&>(rhs);         j = rhs.j;         return *this;     } };  int main() {     x;     b y;     b z;     ...     y = x; // ok     y = z; // ok     ...         return 0; } 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -