Assign derived class to base class
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开发者_如何学Python x;
Derived y;
x = y; // safe?
Do the extra bits in derived classes just get sliced off?
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!
精彩评论