Feb 24
Feb 24
CODE:
#include <iostream>
#include <cstring>
class MyString {
private:
char* str;
size_t length;
public:
MyString() : str(nullptr), length(0) {}
MyString(const char* s) {
length = strlen(s);
str = new char[length + 1];
strcpy(str, s);
}
MyString(const MyString& other) {
length = other.length;
str = new char[length + 1];
strcpy(str, other.str);
}
MyString& operator=(const MyString& other) {
if (this != &other) {
delete[] str;
length = other.length;
str = new char[length + 1];
strcpy(str, other.str);
}
return *this;
}
~MyString() {
delete[] str;
}
void setString(const char* s) {
delete[] str;
length = strlen(s);
str = new char[length + 1];
strcpy(str, s);
}
const char* getString() const {
return str;
}
std::ostream& operator<<(std::ostream& os) const {
if (str) {
os << str;
}
return os;
}
std::istream& operator>>(std::istream& is) {
char buffer[1000];
is >> buffer;
setString(buffer);
return is;
}
};
std::ostream& operator<<(std::ostream& os, const MyString& obj) {
return os << obj.getString();
}
std::istream& operator>>(std::istream& is, MyString& obj) {
return obj >> is;
}
int main() {
MyString s1("Hello");
MyString s2;
std::cout << "Enter a string: ";
std::cin >> s2;
std::cout << "You entered: " << s2 << std::endl;
return 0;
}
OUTPUT:
NOTES:
Shallow Copy vs. Deep Copy
Shallow Copy: Copies only the memory address; changes in one affect the other.
Deep Copy: Allocates new memory and copies content, ensuring independent
objects.
Copy Constructor vs. Assignment Operator
Copy Constructor (ClassName(const ClassName& obj)): Used when creating a new
object from an existing one.
Assignment Operator (operator=(const ClassName& obj)): Used to copy content
between existing objects.