Tuesday, September 13, 2011

Problem of using default Copy Constructor, when Class new some data

In case of there are some data is created in a class using new, if we create another new object using compiler auto generated default copy constructor; the default copy constructor copy the pointer only, without create the new data. Both object have the same data, such that changing the data in one object will affect in the another object.

It's a example:
Problem of using default Copy Constructor, when Class new some data

#include <iostream>

using namespace std;

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

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

}

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;
}

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

MyClass myClass2(myClass1); //Using default Copy Constructor
myClass2.getInfo();

/*
* Both myClass1.ptToChar and myClass2.ptToChar point to
* the same char[size], such that fill in myClass1 affect
* the array also!!!
*/
myClass1.fill('B');
myClass2.getInfo();
return 0;
}




we can provide our own copy constructor to solve the problem.

No comments:

Post a Comment