开发者

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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜