operator=() in base and derived class
Dear members of this group,
recently I came across a problem with repsect to operator=() and
inheritance. Consider the following code snippet:
------------------------------------------------------------
#include <iostream>
using namespace std;
class A
{
public:
A & operator=(const A &_a) {
cout << " in A" << endl;
}
};
class B : public A
{
public:
B & operator=(const A &_a) {
cout << " in B" << endl;
A::operator=(_a);
}
};
main()
{
B b1, b2;
A a;
b1=b2;
cout << endl;
b1=a;
}
----------------------------------------
If you run this program (compiled using gcc 3.3 and 4.1), the output
you get is:
-------------------
in A
in B
in A
------------------
This means:
* for the assignment b1=b2, A::operator=() is invoked
* for b1=a, B::operator=() is invoked.
Now the solution to make the code behave as intended by me is to add
another function
B & operator=(const B&_B) {
cout << " in B" << endl;
A::operator=(_b);
}
However, I don't understand the reasons for this behaviour and I'd
like to understand that. What are the rationales behind that behaviour?