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.
I think the book says "may slice" in
naive, because if you pass pointer toBasein, then slicing will not occur - you will copyBasetoBase. Inuser, you have very clearly aDerivedobject, so the slicing will occur.In other words,
naivedoesn't know what type is in the pointer, so slicing is only potential (from this function perspective), butuserknows 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.