1// Constructor Member Initializer List
2
3#include <iostream>
4
5class Example
6{
7private:
8 int x, y;
9
10public:
11 Example() : x(0), y(0) {}
12 Example(int x1, int y1) : x(x1), y(y1) {}
13 ~Example() {}
14};
15
16int main()
17{
18 Example e;
19}
1struct S {
2 int n;
3 S(int); // constructor declaration
4 S() : n(7) {} // constructor definition.
5 // ": n(7)" is the initializer list
6};
7
8S::S(int x) : n{x} {} // constructor definition. ": n{x}" is the initializer list
9
10int main() {
11 S s; // calls S::S()
12 S s2(10); // calls S::S(int)
13}
1#include <iostream>
2class Entity {
3private :
4 std::string m_Name;
5 int m_Score;
6 int x, y, z;
7public:
8 Entity()
9 :m_Name("[Unknown]"),m_Score(0),x(0),y(0),z(0)//initialize in the order of how var are declared
10 {
11 }
12 Entity (const std::string& name)
13 :m_Name(name)
14 {}
15 const std::string& GetName() const { return m_Name; };
16};
17int main()
18{
19 Entity e1;
20 std::cout << e1.GetName() << std::endl;
21 Entity e2("Caleb");
22 std::cout << e2.GetName() << std::endl;
23 std::cin.get();
24}
1class Something
2{
3private:
4 int m_value1;
5 double m_value2;
6 char m_value3;
7
8public:
9 Something()
10 {
11 // These are all assignments, not initializations
12 m_value1 = 1;
13 m_value2 = 2.2;
14 m_value3 = 'c';
15 }
16};
17
1class Example {
2public:
3 int m_A, m_B, m_C;
4 Example(int a, int b, int c);
5};
6
7Example::Example(int a, int b, int c):
8 // This is an initializer list
9 m_A(a),
10 m_B(b),
11 m_C(c)
12{ /* Constructor code */ }
13