Can I cast a derived class to a private base class, using C-style cast?

…衆ロ難τιáo~ 提交于 2019-11-26 11:28:55

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/17925124/can-i-cast-a-derived-class-to-a-private-base-class-using-c-style-cast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!