对象切割(object slicing)

对象切割(object slicing)

Content #

对象切割(object slicing)是 C++ 特有的一种编码错误,这是一种什么错误?

In C++, a derived class object can be assigned to a base class object, but the other way is not possible.

class Base { int x, y; };
class Derived : public Base { int z, w; };
int main()
{
        Derived d;
        Base b = d; // Object Slicing, z and w of d are sliced off
}

Object slicing happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object.

From #