C++: Protected Class Constructor

余生长醉 提交于 2019-12-08 16:23:34

问题


If a class is always going to be inherited, does it make sense to make the constructor protected?

class Base
{
protected:
    Base();
};

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

Thanks.


回答1:


That only makes sense if you don't want clients to create instances of Base, rather you intend it to be base-class of some [derived] classes, and/or intend it to be used by friends of Base (see example below). Remember protected functions (and constructors) can only be invoked from derived classes and friend classes.

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

class Sample
{
 public:
   Sample()
   {
      //invoking protected constructor
      Base *p = new Base();
   }
};



回答2:


If it's always going to be a base (a "mixin"), yes. Keep in mind a class with pure virtual functions will always be a base, but you won't need to do this since it cannot be instantiated anyway.

Also, give it either a public virtual destructor or a protected non-virtual destructor.



来源:https://stackoverflow.com/questions/4524325/c-protected-class-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!