开发者

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

开发者 https://www.devze.com 2023-03-05 08:59 出处:网络
Suppose I have two classes A, and B. B is derived from A. A has no data members, however B has two integer members.

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

精彩评论

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

关注公众号