-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathctor_example.cpp
More file actions
79 lines (58 loc) · 1.45 KB
/
ctor_example.cpp
File metadata and controls
79 lines (58 loc) · 1.45 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
#include <iostream>
using namespace std;
class Example
{
private:
int a, b;
public:
// using constructor initialization list improves performance rather than
// using assignment operator inside the body to initialize
Example ():a(0), b(0)
{
cout << "Default constructor called " << endl;
}
Example (int i, int ii):a(i), b(ii)
{
cout << "Parametrized constructor called " << endl;
}
Example (Example &eg)
{
cout << "Copy constructor called " << endl;
a = eg.a;
b = eg.b;
}
Example & operator= (Example &from)
{
cout << "Assignment operator called " << endl;
a = from.a;
b = from.b;
return *this;
}
~Example ()
{
cout << "Destructor called " << endl;
}
};
// Pass by value.
static Example
do_nothing (Example eg_pas_val)
{
return eg_pas_val;
}
int
main ()
{
// default constructor gets called
Example eg_default;
// Parametrized constructor gets called
Example eg_ovl (5,6);
// Copy constructor gets called
Example eg_cop (eg_ovl);
// Calls the copy constructor twice. One will passing the value and one while returning.
// A temporary object is created and destroyed implicitly while returning the value.
// Destructors for two objects is called
do_nothing (eg_cop);
// Assignment operator called
eg_default = eg_cop;
// Destructors for three objects is called
}