Why is protected constructor raising an error this this code?

后端 未结 4 1240
终归单人心
终归单人心 2020-11-28 12:38

One question about protected constructor. I learnt that the protected constructor can be used in the derived class. How ever, I found the code below has an error. Why does i

4条回答
  •  误落风尘
    2020-11-28 13:19

    When a base class has a protected constructor, you can't instantiate the class directly. But you can do this to call the constructor from the base class constructor:

    class A {
    
    protected:
       A() {}
    };
    
    class B: public A {
    public:
       B() : A() // allowed to access constructor like this
       {
          A* f = new A(); // Not allowed to access constructor like this!
       }
    };
    

    A direct call to the constructor as shown below gives you the following error with gcc version 4.1.2:

          A* f = new A(); // Not allowed to access constructor like this!
    
    test.cpp:4: error: A::A() is protected
    

    However, you this call to the constructor gives no errors:

       B() : A() // allowed to access constructor like this
    

    The reason behind this is that the second call accesses the A() constructor through inheritance, which is allowed. However, this tries to explicitly create a new instance of A() by calling the constructor directly:

          A* f = new A(); // Not allowed to access constructor like this!
    

    This might seem unintuitive, as B should be able to access A's constructor because B inherits from A. However, if you declare a constructor protected in C++, you can't create an instance of that class except through inheritance or a friend relationship.

提交回复
热议问题