Question

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?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top