2

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..

StackUser
  • 309
  • 2
  • 10
  • You can look at [What is object slicing?](https://stackoverflow.com/questions/274626/what-is-object-slicing) for examples. Note that none of the answers there actually explain what is the problem with it (including fgp's answer, even though it claims otherwise). – user7860670 Mar 15 '18 at 10:05
  • kudos for your patience. Actually I dont know what the SO etiquette says about deleting a closed question to repost it, but I am glad to see that you managed to improve your question considerably and that eventually you got an answer. – 463035818_is_not_an_ai Mar 15 '18 at 10:24

1 Answers1

6

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;
Sean
  • 60,939
  • 11
  • 97
  • 136