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

前端 未结 3 597
说谎
说谎 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: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.

提交回复
热议问题