Peter87 wrote: |
---|
What you're doing when you initialize the vector is called slicing. |
I read a bit about it but it looks like it can happen in many situations.
1. When a method parameter takes a pointer-to-base-type and it's passed a pointer-to-derived-type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
// [1]
struct Foo { ... };
struct Fooz : Foo { ... };
struct BigBox
{
bool getFoo(Foo *fillMe) { ... }
}
BigBox theBigBox;
int main()
{
Fooz fz;
theBigBox.getFoo(&fz); // mbozzi: slices fz since BigBox::getFoo takes Foo*
}
|
2. When a base type is assigned a derived type.
1 2 3 4 5 6
|
// [2] "The benign case"
struct A { int w=0, x=1; };
struct B : public A { int y=2, z=3; };
B b;
A a = b; // Slicing b.y, b.z
|
3. When a reference to a base type is initialized with a derived type
1 2 3 4 5 6
|
// [2] "The treacherous case"
B b1;
B b2;
b2.w = -2; b2.x = -1; b2.y = 4; b2.z = 5; // Change b2 a bit
A& a_ref = b2;
a_ref = b1; // Slicing occurs during copy assignment; only b1's A:: members are copied. C++ doesn't treat assignment operator as virtual by default.
|
And now, it can happen when initializing a vector (and I'm guessing any other containers). Is that because the initializer list:
1 2 3 4 5 6
|
auto faces = vector<DieFace>
{
MonsterFace(-2000), MonsterFace(4000),
StarFace(1000), StarFace(-3000),
DieFace(1), DieFace(2), DieFace(3), DieFace(4), DieFace(5), DieFace(6)
};
|
performs a copy assignment of those derived objects to DieFace (base) objects on the heap?
Maybe my error was assuming that heap-allocation somehow prevented slicing. The fact that those DieFace objects are heap-allocated won't prevent slicing, right?
In a way, I can see that it vaguely resembles case 2, "The benign case", except where
A
is stack-allocated, storage for those derived objects just happen to be heap-allocated.
... yup. Visual Studio also says this is slicing:
1 2
|
A *a = new A(); // Storage for a is heap-allocated
*a = b1; // Still slicing.
|
[1] Storing Items In an Array of Custom Lists
https://cplusplus.com/forum/beginner/284285/
[2] SO: What is object slicing?
https://stackoverflow.com/a/274634/5972766