forked from cirosantilli/cpp-cheat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
constructor_init_object_member.cpp
59 lines (51 loc) · 1.5 KB
/
constructor_init_object_member.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
/*
https://stackoverflow.com/questions/12927169/how-can-i-initialize-c-object-member-variables-in-the-constructor
Initializer lists are the only way to not call the extra default constructor + assignement apparently.
This is a major use case of initializer lists.
They are not very versatile however, as you can't easily have multiple statements.
*/
#include "common.hpp"
class MyMemberClass {
public:
int i;
MyMemberClass() : i(0) {
callStack.push_back("MyMemberClass()");
}
MyMemberClass(int i) : i(i) {
callStack.push_back("MyMemberClass(int i)");
}
MyMemberClass& operator=(const MyMemberClass& rhs) {
this->i = rhs.i;
callStack.push_back("operator=");
return *this;
}
};
class MyClass {
public:
MyMemberClass myMemberClass;
MyClass(int i) : myMemberClass(i) {}
};
class MyClassNoInitializer {
public:
MyMemberClass myMemberClass;
MyClassNoInitializer(int i) {
myMemberClass = MyMemberClass(i);
}
};
int main() {
// Good, less calls.
{
callStack.clear();
MyClass myClass(1);
assert(myClass.myMemberClass.i == 1);
assert(callStack.size() == 1);
assert(callStack.back() == "MyMemberClass(int i)");
}
// Bad, more calls.
{
callStack.clear();
MyClassNoInitializer myClass(2);
assert(myClass.myMemberClass.i == 2);
assert(callStack.size() == 3);
}
}