Search code examples
c++classinheritanceobject-slicing

When I get a case of `slicing`?


Let's look the next code (for example):

class A {
    int n;
public:
    int f() const { return n; }
    void set(int i) { n = i; }
};
class B : public A {
public:
    int g() const { return f()+1; }
};
void h(const A& a) {
    a.f();
}
int main() {
    B b;
    A& a = b;
    A* ptrA = new B; 
    h(b);
  delete ptrA;
    return 0;
}

Now, Let's look about these lines code:

A& a = b; // Is there "slicing"? (why?)
A* ptrA = new B; // Is there "slicing"? (why?)
A a = b; // Is there "slicing"? (why?)

I do not really understand when I want to use any of them, and when, alternatively, you will not be allowed to use one of them. What is really the difference between these lines..


Solution

  • Slicing is when you assign a derived object to a base instance. For example:

    B b;
    A a = b;
    

    The issue here is that the copy constructor for A that is being called only sees the A part of B, and so will only copy that. This is an issue if your derived class has added additional data or overridden the behaviour of A.

    When you assign an object to a reference or a pointer there is no slicing. So

    A &a = b;
    

    Is fine, as is:

    A *a = &b;