Re: operator=() in base and derived class
On Oct 22, 4:44 am, MWimmer <michael.wimm...@gmx.de> wrote:
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?
The compiler will implicily create an assignment operator, that just
calls assignment for member and base.
The only way not to get this is to define one yourself, that takes the
type as an argument. In this case, B&operator=(A const&); does not
turn off this implictly generated function.
The complier made up a function for you that looks like
B&operator=(B const&b){
A::operator=(b);
}
Why does it do this? This is more to support some coding styles that
are essentially mixtures of C and C++. So in C we may have
struct A{
int g;
char buf[123];
};
struct B{
A a;//C version of inheritance
double d[543];
};
void foo(){
struct B b1,b2;
b1=b2;//C does a implicit memcpy underneath the hood
}
So you can see that the "implicit operator=" is a holdover from C.
when this is converted to C++, it may look like
struct A1{
int g;
std::string buf;
};
struct B1:A1{
std::vector<double> d;
};
void foo1(){
struct B1 b1,b2;
b1=b2;//C++ does a member by member operator= underneath the hood
//because string and vector will not survive a memcpy
}
Lance