• Advertisement
Sign in to follow this  

Confusing copy operation in C++

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
Quote:

MSDN
All overloaded operators except assignment (operator=) are inherited by derived classes.

Share this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by waterwalk
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...


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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement