First commit
[cpp_sandbox.git] / Sandbox / DefaultMethods.cpp
1 #include "DefaultMethods.h"
2
3 #include <iostream>
4 using namespace std;
5
6 namespace DefaultMethods
7 {
8 class C
9 {
10 int a;
11
12 public:
13 // Default constructor (here we remove the default one).
14 C() = delete;
15
16 // Copy constructor.
17 C(const C& other);
18
19 // Move constructor.
20 C(C&& other) noexcept;
21
22 // A custom constructor.
23 C(int a);
24
25 // Copy-assignment operator.
26 C& operator=(const C& other);
27
28 // Move-assignment operator.
29 C& operator=(C&& other) noexcept;
30
31 ~C() noexcept;
32
33 int getA();
34 };
35
36 C::C(const C& other)
37 {
38 cout << "Copy ctor, other.a = " << other.a << endl;
39 this->a = other.a;
40 }
41
42 C::C(C&& other) noexcept
43 {
44 cout << "Move ctor, other.a = " << other.a << endl;
45 this->a = other.a;
46 other.a = 0;
47 }
48
49 C::C(int a)
50 : a{ a }
51 {
52 cout << "ctor, a = " << a << endl;
53 }
54
55 C& C::operator=(const C& other)
56 {
57 cout << "Copy assignment operator" << endl;
58 this->a = other.a;
59 return *this;
60 }
61
62 C& C::operator=(C&& other) noexcept
63 {
64 cout << "Move assignment operator" << endl;
65 this->a = other.a;
66 other.a = 0;
67 return *this;
68 }
69
70 C::~C() noexcept
71 {
72 cout << "Destructor, a = " << this->a << endl;
73 }
74
75 int C::getA()
76 {
77 return this->a;
78 }
79 }
80
81 void DefaultMethods::tests()
82 {
83 // Use of universal initialization.
84 C c1{ 42 };
85
86 C c2 = move(c1); // Force to treat 'c1' as a right-hand value.
87 C c3{ c1 };
88 C c4{ 42 };
89 cout << "c1.a = " << c1.getA() << endl;
90 cout << "c2.a = " << c2.getA() << endl;
91 cout << "c3.a = " << c3.getA() << endl;
92 cout << "c4.a = " << c4.getA() << endl;
93
94 cout << "--- copy some values" << endl;
95 c1 = c2;
96 c2 = C{ 321 };
97 cout << "c1.a = " << c1.getA() << endl;
98 cout << "c2.a = " << c2.getA() << endl;
99 }