// this program demonstrates the need for a copy constructor #include using namespace std; class MyClass { private: char* str; public: MyClass(); MyClass(const MyClass& obj); // the copy constructor void Print(); ~MyClass(); //destructor }; MyClass::MyClass() { cout << "In constructor ..." << endl; str = new char(50); strcpy(str, "Hello World"); } MyClass::MyClass(const MyClass& obj) { cout << "In copy constructor ..." << endl; str = new char(50); strcpy(str, obj.str); } void MyClass::Print() { cout << str << endl; } MyClass::~MyClass() { cout << "In destructor ..." << endl; delete str; } int main() { MyClass* obj1 = new MyClass(); obj1->Print(); MyClass obj2(*obj1); delete obj1; // but a copy is being pointed to by obj2 cout << "Here is the garbage: " ; obj2.Print(); // this produces garbage getchar(); return 0; }