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.
Yes, that is explicitly allowed. Alexandrescu uses this extensively in Modern C++ Design for his approach of policy based design:
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:
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.
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
Edit 2: make the answere more detail.
Yes you can: §5.4/7 of the standard:
But try not to as it defeats the purpose of private inheritance.