Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Base on your question title, the answere depends. But for your case in your source code, the answere is yes.

There are two factor which will impact the answere:

  1. If you using C style cast, it will yes, because cast will call re-interpert cast if no conversion availible. You can cast any type of pointer to the target type of pointer. But if there is MI, the result may be incorrect for most C++ language implementation.

  2. If you do the cast (without C style cast) inside the memeber function, the answere will be yes, because the base class is accessable inside the member function. If the expression is in the location where the base class is inaccessable, you will got compile error.

There are more detail about standard converstion in the C++ standard

A prvalue of type “pointer to cv D”, where D is a class type, can be converted to a prvalue of type “pointer to cv B”, where B is a base class (Clause 10) of D. 
If B is an inaccessible (Clause 11) or ambiguous (10.2) base class of D, a program that necessitates this conversion is ill-formed. 
The result of the conversion is a pointer to the base class subobject of the derived class object. The null pointer value is converted to the null pointer value of the destination type.

Edit 2: make the answere more detail.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top