简体   繁体   中英

C++ protected ctor not available to members in derived class

If I declare a derived class which also includes an additional member of base type, I get a "constructor is protected" error.

test.cpp:

class Base { protected: Base() {} };

class Derived1 : public Base
  {
    Derived1()  {}
  };

class Derived2 : public Base
  {
    Derived2()  {}
    Base    other_base;
  };

$ g++ test.cpp

test.cpp: In constructor ‘Derived2::Derived2()’:
test.cpp:3:25: error: ‘Base::Base()’ is protected
 class Base { protected: Base() {} };
                         ^
test.cpp:12:14: error: within this context
  Derived2()  {}

If I declare Derived2 as a friend of Base, the error goes away. Can anyone explain what's happening here?

TIA.

这是因为other_base实际上不是Derived2类的一部分,它是一个单独的对象,遵循公共/受保护/私有成员的常规规则。

The problem is that Derived2 contains an instance of Base .

Accessibility of protected members is only in the context of a derived class instance accessing members it has inherited. It does not allow construction of members with protected constructors.

Therefore Derived2 's constructor cannot construct other_base , but can construct the Base it inherits from.

Declaring Derived2 as a friend of Base allows other_base to be constructed.

In your example other_base is treated like a member of your Derived2 class, and it follows normal access rules. The only place where you can call your protected Base() ctor is initzialization list of Derived2 ctor:

Derived2() : Base() {}

If u want use protected/private methods/members use friend keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM