What is copy assignment operator in C++?
- The copy assignment operator allows to assign objects of same class to each other by overloading '=' operator.
- The compiler automatically generates this member function if is not defined explicitly.
- The generated copy assignment funcion does a bit wise copy or in other words shallow copy.
- If our class has dynamically allocated members then it becomes necessary to write our own implementation of copy assignment function to perform a deep copy.
EXAMPLE: Demonstrate the usage of copy assignment operator
#include <iostream>
using namespace std;
class MyClass {
private:
char* str;
public:
MyClass();
MyClass(char* aStr);
MyClass& operator=(const MyClass& obj);
void Print();
~MyClass();
};
MyClass::MyClass() {
}
MyClass::MyClass(char* aStr) {
cout << "In constructor ..." << endl;
str = strdup(aStr);
}
// Copy assignment
MyClass& MyClass::operator=(const MyClass& other) {
cout << "In copy assignment ..." << endl;
str = strdup(other.str);
return *this;
}
void MyClass::Print() {
cout << str << endl;
}
MyClass::~MyClass() {
cout << "In destructor ..." << endl;
delete str;
}
void main()
{
// Create obj1
MyClass* obj1 = new MyClass("Hello World");
obj1->Print();
// Assignment. obj1 to obj2
MyClass obj2;
obj2 = *obj1;
// Cleanup obj1
delete obj1;
obj2.Print();
}
OUTPUT:-
In constructor ...
Hello World
In copy assignment ...
In destructor ...
Hello World
In destructor ...
I have been visiting various blogs for my term papers writing research. I have found your blog to be quite useful. Keep updating your blog with valuable information... Regards
ReplyDelete