geeksforgeeks 027-默认构造函数

默认构造函数:没有任何参数,或者每个参数都有默认值的构造函数。
如果程序员没有声明构造函数,编译器将会隐式的声明
编译器会根据环境生成默认的构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
using namespace std;

class Base
{
public:

};

class A
{
public:
// User defined constructor
A()
{
cout << "A Constructor" << endl;
}

// uninitialized
int size;
};

class B : public A
{
// compiler defines default constructor of B, and
// inserts stub to call A constructor

// compiler won't initialize any data of A
};

class C : public A
{
public:
C()
{
// User defined default constructor of C
// Compiler inserts stub to call A's construtor
cout << "B Constructor" << endl;

// compiler won't initialize any data of A
}
};

class D
{
public:
D()
{
// User defined default constructor of D
// a - constructor to be called, compiler inserts
// stub to call A constructor
cout << "D Constructor" << endl;

// compiler won't initialize any data of 'a'
}

private:
A a;
};

int ()
{
Base base;

B b;
C c;
D d;

return 0;
}

output:

1
2
3
4
5
A Constructor
A Constructor
B Constructor
A Constructor
D Constructor