-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12.8 MyStringCopyAssignmentOperator.cpp
More file actions
79 lines (65 loc) · 1.57 KB
/
12.8 MyStringCopyAssignmentOperator.cpp
File metadata and controls
79 lines (65 loc) · 1.57 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>
#include <string.h>
using namespace std;
class MyString
{
private:
char* buffer;
public:
MyString(const char* initialInput)
{
if(initialInput != NULL)
{
buffer = new char [strlen(initialInput) + 1];
strcpy(buffer, initialInput);
}
else
buffer = NULL;
}
// Copy assignment operator
MyString& operator= (const MyString& CopySource)
{
if ((this != &CopySource) && (CopySource.buffer != NULL))
{
if (buffer != NULL)
delete[] buffer;
// ensure deep copy by first allocating own buffer
buffer = new char [strlen(CopySource.buffer) + 1];
// copy from the source into local buffer
strcpy(buffer, CopySource.buffer);
}
return *this;
}
operator const char*()
{
return buffer;
}
~MyString()
{
delete[] buffer;
}
MyString(const MyString& CopySource)
{
cout << "Copy constructor: copying from MyString" << endl;
if (CopySource.buffer != NULL)
{
// ensure deep copy by first allocating own buffer
buffer = new char[strlen(CopySource.buffer) + 1];
// copy from the source into local buffer
strcpy(buffer, CopySource.buffer);
}
else
buffer = NULL;
}
};
int main()
{
MyString string1("Hello ");
MyString string2(" World");
cout << "Before assignment: " << endl;
cout << string1 << string2 << endl;
string2 = string1;
cout << "After assignment string2 = string1: " << endl;
cout << string1 << string2 << endl;
return 0;
}