您的位置:首页 > 编程语言 > C语言/C++

compiler-generated default constructor

2014-08-05 10:51 281 查看
Concept:

Default constructor is the constructor that takes no argument, also called 0-argument constructor.

The compiler will generate the default constructor if the user does not implement ANY type of constructor. For example:

// Example 1
struct A
{
int a;
}

A my_a; // Works! Compiler generates the default constructor.


However,

// Example 2
struct A
{
A( int i ) {};
int a;
}

A my_a; // Fails! Compiler doesn't generate the default constructor
// because the user has specified one already.


To make Example 2 work, we need to provide the default constructor as well:

// Example 3
struct A
{
A() {}; // user defined default constructor
// with implementations in { }, even though it's void.
A( int i ) {};
int a;
}

A my_a; // Works! Default constructor is provided.

Or, to take advantage of C++11,

// Example 4
struct A
{
A() = default; // compiler-generated default constructor
// without the need of implementation ---> no { }
A( int i ) {};
int a;
}

A my_a; // Works! Default constructor is provided.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++11 constructor
相关文章推荐