Reputation:
Exactly as the question states!
Let's say I have the following snippet
class A
{
int x;
int y;
}
class B : public A
{
int z;
}
class C
{
A a;
public C(A a) : a(a){}
}
What would happen if I called C's constructor with a B class, would it copy it's A part data in the class? Or also keep it's B data somewhere?
Thanks in advance! It might be a stupid question but I never understood actually.
Upvotes: 2
Views: 111
Reputation: 16243
If you pass an instance of B
to the C
constructor that takes an A
by value, the B
instance will be sliced, and just the A
part will remain. So :
would it copy it's A part data in the class?
this.
So, specifically, there is no way to turn the C::a
member back into a B
instance with the same value for z
as the original B
instance - that information has been lost during the (irreversible) slicing operation.
Upvotes: 5
Reputation: 254631
What would happen if I called C's constructor with a B class, would it copy it's A part data in the class?
Yes. This is known as slicing - the argument is created using A
's copy constructor, which just copies the A
subobject.
Or also keep it's B data somewhere?
No.
Upvotes: 3