Trouble with inheritance of operator= in C++ -


i'm having trouble inheritance of operator=. why doesn't code work, , best way fix it?

#include <iostream>  class { public:     & operator=(const & a)     {         x = a.x;         return *this;     }      bool operator==(const & a)     {         return x == a.x;     }      virtual int get() = 0; // abstract  protected:     int x; };  class b : public { public:     b(int x)     {         this->x = x;     }      int get()     {         return x;     } };  class c : public { public:     c(int x)     {         this->x = x;     }      int get()     {         return x;     } };  int main() {     b b(3);     c c(7);     printf("b: %d c: %d b==c: %d\n", b.get(), c.get(), b==c);      b = c; // compile error     // error: no match 'operator= in 'b = c'     // note: candidates b& b::operator=(const b&)      printf("b: %d c: %d b==c: %d\n", b.get(), c.get(), b==c);     return 0; } 

if not declare copy-assignment operator in class, compiler declare 1 implicitly. implicitly declared copy-assignment operator hide inherited assignment operators (read "name hiding" in c++), meaning inherited assignment operators become "invisible" unqualified name lookup process (which happens when b = c), unless take specific steps "unhide" them.

in case, class b has no explicitly declared copy-assignment operator. mean compiler declare

b& b::operator =(const b&) 

implicitly. hide operator inherited a. line

b = c; 

does not compile, because, candidate here above implicitly declared b::operator = (the compiler told already); other candidates hidden. , since c not convertible b&, above assignment not compile.

if want code compile, can use using-declaration unhide inherited a::operator = adding

using a::operator =; 

to definition of class b. code compile, although won't style. have keep in mind in case b = c assignment invoke a::operator =, assigns a portions of objects involved. (but apparently intent.)

alternatively, in cases can work around name hiding using qualified version of name

b.a::operator =(c); 

Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -