This topic is 4185 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

For the following code, I get this output: A::operator= 1 2 0 4 Can you tell me if my logic is correct? The "dummy1 = dummy2;" statment invokes the implicitly defined B::operator=, which copies B::d, then A::operator= is called..? Can someone explain where the "0" came from?
#include <iostream>
using namespace std;

class A
{
public:
A() : a(0), b(0), c(0) {}
int a;
int b;
int c;

A& operator= (A& rhs)
{
a = rhs.a;
b = rhs.b;
cout << "A::operator=()" << endl;
return *this;
}
};

class B : public A
{
public:
B() : d(0) {}

int d;
};

int main()
{
B dummy1;
B dummy2;

dummy2.a = 1;
dummy2.b = 2;
dummy2.c = 3;
dummy2.d = 4;

dummy1 = dummy2;

cout << dummy1.a << endl;
cout << dummy1.b << endl;
cout << dummy1.c << endl;
cout << dummy1.d << endl;

return 0;
}



##### Share on other sites
A& operator= (A& rhs)	{		a = rhs.a;		b = rhs.b;		cout << "A::operator=()" << endl;		return *this;	}

you forgot to set c to rhs.c.

##### Share on other sites
I did that on purpose, as a test case. I wanted to see if the derived B::operator= would copy *all* members. But apparently A::operator= is still called.

I read that if you defined your own B::operator=, then A::operator= is not called. So, if I wanted added functionality in B::operator=, but still wanted A::operator= to be called for an object, I would have to invoke A::operator=() explicitly within B::operator= ?

Just trying to figure out the details of operator inheritance...

Thanks.

##### Share on other sites
Quote:
 Original post by discman1028if I wanted added functionality in B::operator=, but still wanted A::operator= to be called for an object, I would have to invoke A::operator=() explicitly within B::operator= ?

yes

##### Share on other sites
The zero clearly comes from dummy1 itself. You don't replace 'c' with a new value, so it keeps the value it had originally. In this case, it happens to be 0.

Bs assignment operator isn't going to mess with As members...that's what As assignment operator is there for.

CM

##### Share on other sites
Thanks, makes sense.

##### Share on other sites
Quote:
 Original post by discman1028I did that on purpose, as a test case. I wanted to see if the derived B::operator= would copy *all* members. But apparently A::operator= is still called.

Copying a B obviously involves copying the A sub-object. Like every other member of B, if it has its own copy operator, that will get called.

Quote:
 I read that if you defined your own B::operator=, then A::operator= is not called. So, if I wanted added functionality in B::operator=, but still wanted A::operator= to be called for an object, I would have to invoke A::operator=() explicitly within B::operator= ?

Correct.