-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy_constructor.cpp
More file actions
57 lines (43 loc) · 1.31 KB
/
Copy pathcopy_constructor.cpp
File metadata and controls
57 lines (43 loc) · 1.31 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
// A Program to show an example of copy constructor
#include<iostream>
#include<string>
#include<cstring>
class String {
private:
char* m_Buffer;
unsigned int m_Size;
public:
String(const char* string) {
m_Size = strlen(string);
m_Buffer = new char[m_Size + 1];
memcpy(m_Buffer, string, m_Size);
}
String(const String& other)
:m_Size(other.m_Size) {
std::cout << "copy constructor called" << std::endl;
m_Buffer = new char[m_Size + 1];
memcpy(m_Buffer, other.m_Buffer, m_Size+1);
}
char& operator[](unsigned int index) {
return m_Buffer[index];
}
friend std::ostream& operator<<(std::ostream& stream, const String& string);
~String() {
delete[] m_Buffer;
}
};
void PrintString(const String& a) {
// Here if we pass the argument as String a that leads to the copy of the string
std::cout << a << std::endl;
}
std::ostream& operator<<(std::ostream& stream, const String& string) {
stream << string.m_Buffer;
return stream;
}
int main() {
String name = "Cherno";
String name2 = name;
name[2] = 'a';
PrintString(name);
PrintString(name2);
}