-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path45initializationlist.cpp
More file actions
46 lines (42 loc) · 1.21 KB
/
Copy path45initializationlist.cpp
File metadata and controls
46 lines (42 loc) · 1.21 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
/*
INITIALISATION LIST :
this is a new way of writing a constructor with a new syntax
{{constructor name}} (arg1, arg2) : {{private variable 1}}(arg1), {{private variable 2}}(arg2)
{
constructor body...
}
*/
#include <iostream>
using namespace std;
class Test
{
int a, b; // this order is important to make the order of value initialising in constructor
public:
Test(int x, int y) : a(x), b(y)
{
cout << "This is a constructor" << endl;
cout << a << endl
<< b << endl;
}
/*
OTHER POSSIBLE WAYS TO USE THIS SYNTAX OR POSSIBLE ACCURATE DECLARATION
Test(int x, int y) : a(x), b(x + y){}
Test(int x, int y) : a(x), b(a + y){} Since a is already set
Test(int x, int y) : a(x), b(2 * y){}
Test(int x, int y) : b(y), a(b + x){} --> this is not valid and the value of a will not have b + x but instead a garbage
value, this is due to the declaration or initialising order in the class
Test(int x, int y) : b(x), a(y){} --> Not valid
Test(int x, int y) : a(x){
b = y;
}
Test(int x, int y){ Basic syntax
a = x;
b = y;
}
*/
};
int main()
{
Test obj(2, 4);
return 0;
}