When will I receive the “slicing” case?

See the following 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 look at these lines:

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

I really don't understand when I want to use any of them, and when, as an alternative, you will not be allowed to use one of them. What is the difference between these lines.

+4
source share
1 answer

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

B b;
A a = b;

, A, , A B, . , A.

.

A &a = b;

, :

A *a = &b;
+6

Source: https://habr.com/ru/post/1694906/


All Articles