-
Notifications
You must be signed in to change notification settings - Fork 2
/
allTypeOfConstructor.cpp
77 lines (69 loc) · 1.8 KB
/
allTypeOfConstructor.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
/*
author : aniket
*/
#include "iostream"
using namespace std;
#include "vector"
class Aniket
{
public:
int data;
int *ptr;
//default constructor
Aniket()
{
cout<<" I am in default constructor"<<endl;
data =0;
ptr = new int;
*ptr = 21;
}
//parameterised constructor
Aniket(int input)
{
cout<<" I am in a parameterised constructor"<<endl;
data = input;
ptr = new int;
*ptr = 23;
}
//copy constructor
//reference is used to avoid looping
//const is used to avoid modification in original obj
Aniket(const Aniket & temp)
{
cout<<"I am in a copy constructor"<<endl;
this->data = temp.data;
this->ptr = new int;
this->ptr = temp.ptr;
}
//assign operator
Aniket& operator =(const Aniket & temp)
{
cout<<"I am in a assign operator"<<endl;
data = temp.data;
this->ptr = new int;
this->ptr = temp.ptr;
return *this;
//returning reference to avoid chaining proble eg obj1=(obj2=obj3)=obj6
}
//move constructor
//for concept https://www.youtube.com/watch?v=JAOZjf4KneY
Aniket ( Aniket && temp) //rvalue reference.
{
cout<<" I am in move constructor"<<endl;
this->data = temp.data;
this->ptr = temp.ptr;
temp.ptr = NULL;
}
};
int main()
{
vector<Aniket> v1;
//v1.push_back(Aniket());//default & move constructor(bcz its moving the reference/temporary obj);
Aniket a1;
Aniket a2 = a1;//copy constructor
//v1.push_back(a1);//copy constructor(bcz it copying actual object)
v1.push_back(move(a2));// move constructor gets called
Aniket a3;//default constructor
a3 = a1;//assign operator;
Aniket a5(move(a1));//move constructor;
}