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?
Asked
Active
Viewed 385 times
1
-
Show some code. Converting an object of a derived type to an object of a base type slices the object. That's what slicing means. – Pete Becker Sep 29 '13 at 11:33
1 Answers
5
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.

thelamb
- 486
- 3
- 10
-
I think I understood what you are trying to say...One more thing, Thanks for showing the way to get the base pointer, but is it really needed? – Bhupesh Pant Sep 30 '13 at 16:25
-
2I'm not showing how to get the Base _pointer_. The 'asBase' function slices the Derived object to a Base (note that the return value of asBase is 'Base', not 'Base*' or 'Base&', which both would not slice the object). The whole point is that the slicing cannot be done from outside the scope of Derived, because Base is a private base. This is why you 'need' the slicing to happen inside the scope of Derived. Hope this clarifies things. – thelamb Oct 01 '13 at 07:41