-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFILE16.cpp
More file actions
75 lines (63 loc) · 1.42 KB
/
FILE16.cpp
File metadata and controls
75 lines (63 loc) · 1.42 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
/*
Using the assignment operator and copy constructor we can create a String class.
When we use the overloaded assignment operator to assign one String object to another we copy the string from the source into the destination object.
Now the same string exists in two places in memory.
In the program shown below we will use the String class and provide the full complement of operations such as constructors, copy constructor, overloaded assignment operator, and destructor.
*/
#include <iostream>
#include <cstring>
using namespace std;
class String
{
private:
char* str;
public:
String()
{
}
String(string s) // One-arg constructor
{
cout << "In constructor" << endl;
int size = strlen(s.c_str());
str = new char[size+1];
strcpy(str,s.c_str());
}
String(String& ss) // Copy constructor
{
cout << "In copy constructor" << endl;
str = new char[strlen(ss.str) + 1];
strcpy(str,ss.str);
}
~String() // Destructor
{
delete str;
}
String& operator=(String& ss) // Assignment operator
{
cout << "Assignment invoked" << endl;
str = new char[strlen(ss.str) + 1];
strcpy(str, ss.str);
return *this;
}
void showstring()
{
cout << str << endl;
}
};
int main()
{
String s1("String in memory");
cout << "s1 = ";
s1.showstring();
String s2(s1);
cout << "s2 = ";
s2.showstring();
String s3;
s3=s1;
cout << "s3 = ";
s3.showstring();
String s4 = s1;
cout << "s4 = ";
s4.showstring();
return 0;
}