Can I do this?
class A { ... };
class B : private A
{
const A &foo() const
{
return *((const A *)this);
}
};
Can I take a subclass that inherits privately from a base class and cast it to a public version of its base class? Can I do this without it having virtual methods?
My guess is yes, but I wanted to make sure it's safe / portable.
Private members of the base class cannot be used by the derived class unless friend declarations within the base class explicitly grant access to them.
Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer because object slicing happens when a derived class object is assigned to a base class object.
A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.
Derived class can not access the private members of it's base class. No type of inheritance allows access to private members.
Yes you can: §5.4/7 of the standard:
... the following static_cast and reinterpret_cast operations (optionally followed by a const_cast operation) may be performed using the cast notation of explicit type conversion, even if the base class type is not accessible:
a pointer to an object of derived class type or an lvalue of derived class type may be explicitly converted to a pointer or reference to an unambiguous base class type, respectively;
But try not to as it defeats the purpose of private inheritance.
Yes, that is explicitly allowed. Alexandrescu uses this extensively in Modern C++ Design for his approach of policy based design:
template <typename Policy>
class foo : Policy
{
public:
void do_something()
{
Policy & p = *this;
p.do_something();
}
};
So while the use cases may be limited, there are some out there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With