Tuesday, September 13, 2011

new data in Copy Constructor

Refer to the Problem of using default Copy Constructor, when Class new some data, we can provide our own copy constructor to solve the problem:

#include <iostream>

using namespace std;

class MyClass{
public:
MyClass(const int mSize);
MyClass(MyClass& src);
~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];

}

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

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

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

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




new data in Copy Constructor

No comments:

Post a Comment