-
Notifications
You must be signed in to change notification settings - Fork 160
/
delegating_constructor.cpp
84 lines (77 loc) · 1.7 KB
/
delegating_constructor.cpp
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
# Delegating constructor
Call one constructor from another in a given class.
*/
#include "common.hpp"
int main() {
#if __cplusplus >= 201103L
/* Basic example. */
{
class C {
public:
int i;
C() : C(1) {}
C(int i) : i(i) {}
};
C c;
assert(c.i == 1);
}
/* Nothing prevents recursion. */
{
class C {
public:
int i;
C() : C(1) {}
C(int i) : C() {}
};
/* Segfault because of stack overflow. */
/*C c;*/
}
/* Cannot call multiple constructors of the same class. */
{
class C {
public:
int i;
float f;
/* ERROR. */
/*C() : C(1), C(1.5) {}*/
C(int i) : i(i) {}
C(float f) : f(f) {}
};
}
/*
Cannot initialize anything else when a delegation is used:
http://stackoverflow.com/questions/12190051/member-initialization-while-using-delegated-constructor
*/
{
class C {
public:
int i;
int j;
C() : i(i) {}
//C(int i) : C(), i(i) {}
};
C c;
assert(c.i == 1);
}
/*
Works with inheritance.
TODO: Is this still called a "delegated constructor"?
*/
{
class B {
public:
int i;
B() : i(1) {}
};
class C : public B {
public:
int j;
C() : B(), j(2) {}
};
C c;
assert(c.i == 1);
assert(c.j == 2);
}
#endif
}