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

前端 未结 3 575
说谎
说谎 2020-11-29 11:00

Can I do this?

class A { ... };

class B : private A
{
    const A &foo() const
    {
        return *((const A *)this);
    }
};

Can I

相关标签:
3条回答
  • 2020-11-29 11:37

    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.

    0 讨论(0)
  • 2020-11-29 11:39

    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.

    0 讨论(0)
  • 2020-11-29 11:51

    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.

    0 讨论(0)
提交回复
热议问题