forked from learncppnow/9E
-
Notifications
You must be signed in to change notification settings - Fork 0
/
12.9 CopyAssignmentOperator.cpp
82 lines (68 loc) · 1.79 KB
/
12.9 CopyAssignmentOperator.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
78
79
80
81
82
#include <iostream>
#include <algorithm>
using namespace std;
class MyBuffer
{
private:
int* myNums;
unsigned int bufLength;
public:
MyBuffer(unsigned int length)
{
bufLength = length;
myNums = new int[length]; // allocate memory
}
MyBuffer(const MyBuffer& src) // copy constructor
{
cout << "Copy constructor creating deep copy" << endl;
bufLength = src.bufLength;
myNums = new int[bufLength];
copy(src.myNums, src.myNums + bufLength, myNums); // deep copy
}
MyBuffer& operator= (const MyBuffer& src) // copy assignment
{
cout << "Copy Assignment creating deep copy" << endl;
if (myNums != src.myNums) // avoid copy to self
{
if (myNums)
delete myNums;
bufLength = src.bufLength;
myNums = new int[bufLength];
copy(src.myNums, src.myNums + bufLength, myNums); // deep copy
}
return *this;
}
~MyBuffer()
{
delete[] myNums; // free allocated memory
}
void SetValue(unsigned int index, int value)
{
if (index < bufLength) // check for bounds
*(myNums + index) = value;
}
void DisplayBuf()
{
for (unsigned int counter = 0; counter < bufLength; ++counter)
cout << *(myNums + counter) << " ";
cout << endl;
}
};
int main()
{
cout << "How many integers would you like to store? ";
unsigned int numsToStore = 0;
cin >> numsToStore;
MyBuffer buf(numsToStore);
for (unsigned int counter = 0; counter < numsToStore; ++counter)
{
cout << "Enter value: ";
int valueEntered = 0;
cin >> valueEntered;
buf.SetValue(counter, valueEntered);
}
MyBuffer anotherBuf(1); // initialize to contain just 1 int
anotherBuf = buf;
anotherBuf.DisplayBuf();
return 0;
}