C ++: copy object data to a member function of a base class

Suppose I have two classes A, and B. B is from A. A does not have data elements, however B has two integer members.

If I define a method in class A, as shown below:

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

And call it in the child class, will the integer data member be copied?

+6
source share
2 answers

Not. This is called the cutting problem.

This is true even if you overload operator= both A and B : *this = *other will only allow A::operator=(const A&) or B::operator=(const A&) .

+7
source

Not. this does not hold for members of a child class. This way, members of the Derived class will simply be sliced. This problem is called Object Slicing .

How to solve it?
Prevention is better than cure!

Do not enter code in a situation in which Object Slicing .
If you encounter an Object Slicing problem, you have a poorly designed / developed program. Unless, of course, you sacrifice a good OOP design in favor of expediency.

+3
source

Source: https://habr.com/ru/post/887861/


All Articles