Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

c++ - What is constructor inheritance?

In C++11, what is meant by inheriting the constructor? If it is what i think it is (Base class constructor is brought in the scope of the derived class), what are its implications on my code? What are the applications of such a feature?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Inheriting Constructors means just that. A derived class can implicitly inherit constructors from its base class(es).

The syntax is as follows:

struct B
{
    B(int); // normal constructor 1
    B(string); // normal constructor 2
};

struct D : B
{
    using B::B; // inherit constructors from B
};

So now D has the following constructors implicitly defined:

D::D(int); // inherited
D::D(string); // inherited

Ds members are default constructed by these inherited constructors.

It is as though the constructors were defined as follows:

D::D(int x) : B(x) {}
D::D(string s) : B(s) {}

The feature isn't anything special. It is just a shorthand to save typing boilerplate code.

Here are the gory details:

12.9 Inheriting Constructors

1) A using-declaration that names a constructor implicitly declares a set of inheriting constructors. The candidate set of inherited constructors from the class X named in the using-declaration consists of actual constructors and notional constructors that result from the transformation of defaulted parameters as follows:

  • all non-template constructors of X, and
  • for each non-template constructor of X that has at least one parameter with a default argument, the set of constructors that results from omitting any ellipsis parameter specification and successively omitting parameters with a default argument from the end of the parameter-type-list, and
  • all constructor templates of X, and
  • for each constructor template of X that has at least one parameter with a default argument, the set of constructor templates that results from omitting any ellipsis parameter specification and successively omitting parameters with a default argument from the end of the parameter-type-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...