-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02-2-member-initializer-list.cpp
More file actions
83 lines (62 loc) · 1.41 KB
/
Copy path02-2-member-initializer-list.cpp
File metadata and controls
83 lines (62 loc) · 1.41 KB
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
#include <iostream>
class Student1 {
public:
std::string name;
Student1(std::string n) {
name = n;
}
}; // allocate memory -> create default stirng -> destroy empty string -> copy new string
class Student2 {
public:
std::string name;
Student2 (std::string n) : name(n) {}
}; // allocate memory -> copy new string
class Image {
public:
std::vector<int> pixels;
Image(std::vector<int> p) { pixels = p; }
Image(std::vector<int> p) : pixels(p) {}
};
// Sometime initializer list is necessary
class Student {
public:
const int id;
// Student(int x) { id = x; } // error
Student(int x) : id(x) {}
};
// Reference member
class Teacher {
public:
int& ref;
Teacher(int& r) : ref(r) {}
};
// Base Classes
class Animal {
public:
Animal(int age) {}
};
class Dog : public Animal {
public:
Dog(int age) : Animal(age) {}
Dog(int age) { Animal(age); } // error: Tries to create Dog before Animal
};
// Multiple memebers and initialization order does not matter!
class Student3 {
public:
std::string name;
int age;
double gpa;
// initialization does not matter
Student3(std::string n, int a, double g) : age(a), name(n), gpa(g) {}
};
// In Modern C++ always use initialization list
class Person {
public:
std::string name;
int age;
Person(std::string n, int a)
: name(std::move(n)), age(a) {}
};
int main() {
return 0;
}