tags:

views:

122

answers:

2

Possible Duplicate:
Trouble with inheritance of operator= in C++

hello everyone, let's assume I have two classes:

Base{}; //inside I have operator=
Derived{}; //inside I don't have operator=

why this one is working perfectly:

Derived der1, der2;
der1=der2;  //<-here I know that it actually calls my Base::operator=

and this one is not:

Derived der1;
Base bas1;
der1=bas1;  //<-here why can't call Base::operator=?
+4  A: 

The implicitly declared copy assignment operator looks like

Derived& operator=(const Derived&);

This implicitly declared function calls operator= for each base class and member subobject (this is why the Base class operator= overload is called).

bas1 is of type Base, not Derived, and there is no implicit conversion from Base to Derived, hence it doesn't work. You would need to declare an appropriate assignment operator in order to support assigning an object of type Base to an object of type Derived (this would be a bit unusual though).

James McNellis
@James McNellis: copy c'tor, c'tor and d'tor work the same way?
rookie
@rookie: Yes, effectively.
James McNellis
+2  A: 

That's because

Derived& Derived::operator=(Derived const&);

hides the assignment

Base& Base::operator=(Base const&);

from the base class. This has something to do with name lookup and scopes. Check your favorite C++ book on hiding.

sellibitze