简体   繁体   中英

Object slicing in private inheritance

Why object slicing does not takes place in private inheritance? Static_cast gives error in such cases? I understand that the private inheritance does not hold “is - a” relationship between its inheritance classes. Does this has something to do with slicing since derived is not of type base so compiler is forcing not to do implicit conversion?

It doesn't make any sense to slice a derived class to its private base class. Just consider for a moment what 'private' means. It means that the outside world should not care about it. Allowing slicing (casting) to a private base means the outside world would care.

If you really want this behavior (I'd love to hear your reasons), you can hack around it:

class Base { };
struct Derived : private Base 
{
    Base asBase() { return static_cast<Base>(*this); }
};

This way, the cast happens inside Derived, where Base is accessible. The error you got from static_cast is because it was used outside of the scope of Derived, where Base is not accessible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM