Public Group

# Confusing copy operation in C++

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

## Recommended Posts

Hello, everyone. After reading some c++ text, I wrote some fragments of code to see if I really understand them. I found that I was confused by the following:
class CBase
{
public:
CBase& operator=(CBase& c)
{
printf("CBase::= called\n");
return *this;
}
};

class CDerive : public CBase
{
};

int main()
{
CBase c1, c2;
CDerive d1, d2;

c1 = c2;        //ok
c1 = d1;	//ok
d1 = d2;	//ok, call CBase's operator=
d1 = c1;	//error, why?
system("Pause");
return 0;
}


I can understand why "c1=c2" and "c1=d1" are correct. But I don't know since "d1=d2" is acceptable and their base class's operator= can be called, why "d1=c1" doesn't work. Yes, i know this is something programmers should avoid, but I just want to know the reason behind it. Any ideas?

##### Share on other sites
[edited]

...........I'll just let the post below give the correct answer.............

##### Share on other sites
Quote:
 MSDNAll overloaded operators except assignment (operator=) are inherited by derived classes.

##### Share on other sites
CDerive gets its own, compiler-generated assignment operator regardless of whether CBase has a custom one or not. If you want d1=c1 to work, you will have to give CDerive a custom assignment operator that accepts a CBase parameter. As you point out, since a CBase is not a CDerive, you will have to work out what such an assignment means by yourself.

Note - assignment parameters are generally taken by const reference, unless you plan on modifying the original object, e.g. like std::auto_ptr does.

##### Share on other sites
Well, If CDerive's operator= is really irrelevant to CBase's, as etothex and Fruny pointed out, why in d1=d2, CBase's operator= is called? This is the problem that haunts me...

##### Share on other sites
Quote:
 Original post by waterwalkWell, If CDerive's operator= is really irrelevant to CBase's, as etothex and Fruny pointed out, why in d1=d2, CBase's operator= is called? This is the problem that haunts me...

Because the compiler-generated CDerive::operator= will call CBase::operator= to assign the CBase part of the CDerive object.

• 10
• 18
• 14
• 18
• 15