6

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 data member get copied?

Adsads
  • 61
  • 1

2 Answers2

7

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.

Community
  • 1
  • 1
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • @AtoMerZ: It depends on what you're trying to do. If you ever get into a situation where you have an `A *` that's pointing to a `B`, and you want to `CopyFrom` another `B`, then you're probably doing something wrong! – Oliver Charlesworth May 11 '11 at 17:10
  • 1
    @AtoMerZ: [this answer](http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c/274977#274977) to the linked question gives the best solution. – johnsyweb May 11 '11 at 17:14
3

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.

Alok Save
  • 202,538
  • 53
  • 430
  • 533