开发者

C++: Copy object data in member function of base class

Suppose I have two classes A, and B. B is derived from A. A has no data members, however B has two integer members.

If I define a method in class A, like the following:

void CopyFrom( const A* other )
{
    *this = *other;
}

And call it in the child class, will the integer d开发者_如何学JAVAata member get copied?


No. This is known as the slicing problem.

This is true even if you overload operator= in both A and B: *this = *other will only ever resolve to A::operator=(const A&) or B::operator=(const A&) being called.


No. this doesn't have any space for members of child class. So the members of the Derived class will just get sliced of. This problem is called Object Slicing.

How to solve it?
Prevention is better than cure!

Dont introduce your code to a situation where Object Slicing occurs.
If you are facing the problem of Object Slicing you have a poorly architected/designed software program. Unless, ofcourse you are sacrificing good OOP design in favor of expediency.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜