Is it safe to do the following or is it undefined behaviour:
class Base
{
private:
int a;
};
class Derived : public Base
{
private:
int b;
};
Base x;
Derived y;
x = y; // safe?
Do the extra bits in derived classes just get sliced off?
Let’s consider the example of a base class X: With two derived classes A and B: class A : public X { // ... }; class B : public X { // ... }; If we have two concrete objects that we manipulate through their base class as references to X, how can we implement an assignment operator to assign one into the other?
But you can assign an instance of a derived class to a variable of base class type. You can cast a variable that is typed as the base-class to the type of a derived class; however, by necessity this will do a runtime check, to see if the actual object involved is of the correct type.
The pointer of Base Class pointing different object of derived class: A derived class is a class which takes some properties from its base class. It is true that a pointer of one class can point to other class, but classes must be a base and derived class, then it is possible.
One case comes up often: handling the behaviour of two objects of the same derived class. One case in this special case comes up often: assigning an object to another one. Let’s consider the example of a base class X: With two derived classes A and B: class A : public X { // ... }; class B : public X { // ... };
Yes, slicing occurs. It is not undefined behaviour though.
You might find this entry in the C++-FAQ helpful:
http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8
You are right, the object is sliced. This is a common problem. You shouldn't do it!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With