Thursday, September 11, 2014

C++ Object Slicing

"Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away. For example,
class A {
   int foo;
};

class B : public A {
   int bar;
};
So an object of type B has two data members, foo and bar Then if you were to write this:
B b;

A a = b;
Then the information in b about member bar is lost in a. Situations where problems would arise If You have a base class A and a derived class B, then You can do the following.
void wantAnA(A myA)
{
   // work with myA
}

B derived;
// work with the object "derived"
wantAnA(derived);
Now the method wantAnA needs a copy of derived. However, the object derived cannot be copied completely, as the class B could invent additional member variables which are not in its base class A. Therefore, to call wantAnA, the compiler will "slice off" all additional members of the derived class. The result might be an object you did not want to create, because it may be incomplete, it behaves like an A-object (all special behaviour of the class B is lost).

No comments:

Post a Comment