c++object-slicing

Confusion in example about object slicing in Stroustrup’s book


In section 17.5.1.4 of The C++ Programming Language, there is the following example:

struct Base {
  int b;
  Base(const Base&);
};

struct Derived {
  int d;
  Derived(const Derived&);
};

void naive(Base* p) {
  B b2 = *p;
};

void user() {
  Derived d;
  naive(&d);
  Base bb = d;
};

I’ve omitted the comments in the code, and included the apparent typo in naive() (should be Base b2 ?).

I’m just confused what exactly the issue is here: there is no reason for me to expect a Derived to be copied in either case. I feel as if I ought to be missing something here, but I just cannot understand the point of this “example”.

Can anyone please shed light on this? If this is genuinely an insightful example, I’d like to not be in the dark about it.enter image description here


Solution

  • I think the book says "may slice" in naive, because if you pass pointer to Base in, then slicing will not occur - you will copy Base to Base. In user, you have very clearly a Derived object, so the slicing will occur.
    In other words, naive doesn't know what type is in the pointer, so slicing is only potential (from this function perspective), but user knows the type, so slicing is definitive.

    I agree that the wording is not very obvious here, but it does make sense when interpreted like this.