object slicing is only really a problem if you manipulate derived classes through pointers or references to their base class. Then, the additional data of the derived class remain unchanged, while those in the base part may get altered. This may break invariants of the derived class. For a simple example see http://en.wikipedia.org/wiki/Object_slicing
However, I would consider this a design flaw (of the derived class). If accessing a class by any legal method, including those taken pointer or reference argument to the base class, can break its invariants, the class is badly designed. One way to avoid that is to declare the base private
, so that the derived class cannot legally be accessed via its base.
An example would be:
class A
{
int X;
A(int x) : X(x) {}
void doubleX() { X+=X; }
/* ... */
};
class B : public A
{
int X_square;
B(int x) : A(x), X_square(x*x) {}
/* ... */
};
B b(3);
B.doubleX(); /// B.X = 6 but B.X_square=9
From this example it's also obvious that this is a simple design flaw in B. In this example, providing
void B::doubleX() { A::doubleX(); X_squared=X*X; }
doesn't solve the problem, as
A&a=b;
a.doubleX();
still breaks the invariant. The only solution here is to declare the base A
private or, better, make A
a private member, rather than base, of B
.