Inheritance: 'A' is an inaccessible base of 'B'

后端 未结 6 1345
忘掉有多难
忘掉有多难 2020-11-28 21:51
$ cat inheritance.cpp 
#include 

using namespace std;

class A { };
class B : private A { };

int main() {
    A* ab = new B;
}
$
$ g++ inheritance.         


        
6条回答
  •  情歌与酒
    2020-11-28 22:22

    clang++ gives a slightly more understandable error message:

    example.cpp:9:13: error: cannot cast 'B' to its private base class 'A'
        A* ab = new B;
                ^
    example.cpp:6:11: note: declared private here
    class B : private A { };
              ^~~~~~~~~
    1 error generated.
    

    I'm not a C++ expert, but it looks like it's just simply not allowed. I'll go poke around the spec and see what I come up with.

    Edit: here's the relevant reference from the spec - Section 4.10 Pointer conversions, paragraph 3:

    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 of D. If B is an inaccessible or ambiguous base class of D, a program that necessitates this conversion is ill-formed.

提交回复
热议问题