It's a example:
#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