Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

oop

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?

like image 372
Adsads Avatar asked May 11 '11 17:05

Adsads


1 Answers

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.

like image 107
Oliver Charlesworth Avatar answered Sep 28 '22 01:09

Oliver Charlesworth