Saturday, September 17, 2011

Overloading operator "=" for class with "new" object

Similar to the case in "using default Copy Constructor, when Class new some data". If we assign a object using "new" data inside, it will create a memory leak: because the default "=" operate assign the pointer to new value, without deleting the old data.



Here is a example to overloading operator "=":



#include <iostream>

using namespace std;

class MyClass{
public:
MyClass(const int mSize);
MyClass(MyClass& src);
~MyClass();
void fill(char c);
void getInfo();
MyClass& operator=(const MyClass& src);
private:
int size;
char* ptToChar;
};

//Constructor with default size
MyClass::MyClass(const int mSize = 10)
{
size = mSize;
ptToChar = new char[size];

}

//Copy Constructor
MyClass::MyClass(MyClass& src){
size = src.size;
ptToChar = new char[size];
for(int i = 0; i < size; i++)
ptToChar[i] = src.ptToChar[i];
}

MyClass::~MyClass(){
cout << "MyClass Destructor: " << endl;
}

void MyClass::fill(char c){
for(int i = 0; i < size; i++)
ptToChar[i] = c;
}

void MyClass::getInfo()
{
cout << "size: " << size << endl;
for(int i = 0; i < size; i++)
cout << ptToChar[i];
cout << endl;
}

//Overload operator =
MyClass& MyClass::operator=(const MyClass& src){
if (this != &src){
delete[] ptToChar;

size = src.size;
ptToChar = new char[size];
for(int i = 0; i < size; i++)
ptToChar[i] = src.ptToChar[i];
}
return *this;
}

int main()
{
MyClass myClass1(20);
myClass1.fill('A');
myClass1.getInfo();

MyClass myClass2(10);
myClass2 = myClass1;

myClass2.getInfo();

myClass1.fill('B');
myClass1.getInfo();
myClass2.getInfo();
return 0;
}




Overloading operator


No comments:

Post a Comment