开发者

Assign derived class to base class

开发者 https://www.devze.com 2023-01-17 04:17 出处:网络
Is it safe to do the following or is it undefined behaviour: class Base { private: int a; }; class Derived : public Base

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

精彩评论

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