Just like a copy constructor the compiler provides a default free implementation of the assignment operator for a class. The compiler provided assignment operator implementation does a member-wise copy of the data members. This is often referred to as shallow copying.
| Overload ‘=’ (assignment) operator |
|---|
| // Inside main ( ) { String obj_1 (“EARTH”); String obj_2 (“BLUE”); obj_1 = obj_2; // Resolved as => obj_1 . operator = ( obj_2 ) // This statement leads to the member wise copy that leads to the dangling pointer and memory leakage problem. } |
The shallow copying of the data members give rise to the below problems
C++ program for a String class demonstrates the overloading of assignment operator.
#include<iostream>
#include<cstring>
class String {
private:
u_int m_len;
char* m_buff;
public:
// Default constructor
String () {
m_len = 0;
m_buff = new char;
m_buff[0] = '\0';
}
// Parameterized constructor
String (const char * str) {
m_len = strlen(str);
m_buff = new char[m_len + 1];
strcpy(m_buff, str);
}
// Overloading of = / assignment operator for String class.
// Overload is needed to avoid dangling pointer that would cause errors.
String& operator = (const String& obj) {
if (this != &obj) { // If the source obj is same as the destn object, no need to copy.
m_len = obj.m_len;
delete [] m_buff; // Delete the old buffer of the destination object.
m_buff = new char[m_len+1];
strcpy(m_buff, obj.m_buff);
return (*this);
}
return (*this);
}
~String() {
std :: cout << "Destructor got called." << std :: endl;
if (m_buff) {
delete [] m_buff;
}
}
void Display() {
std :: cout << m_buff << std :: endl;
}
};
int main() {
String s1("Take_It_Easy");
String s2("Hurray");
std :: cout << "String s1 : ";
s1.Display();
std :: cout << "String s2 : ";
s2.Display();
s1 = s2;
std :: cout << "After assignment, String s1 : " ;
s1.Display();
std :: cout << "Main ends. Now returning" << std :: endl;
return 0;
}
Output
String s1 : Take_It_Easy
String s2 : Hurray
After assignment String s1 : Hurray
Main ends. Now returning
Destructor got called.
Destructor got called.
© 2019-2026 Algotree.org | All rights reserved.
This content is provided for educational purposes. Feel free to learn, practice, and share knowledge.
For questions or contributions, visit algotree.org
"Talk is cheap. Show me the code. - Linus Torvalds"