The copy constructor is a mechanism to prevent data loss. For example, if the object being passed contains pointers to dyn. allocated memory. In my case it does not work.
#include "stdafx.h" #include <iostream> using namespace std; class myclass { public: int *var; myclass(int i) { cout << "Obuchnuy konstructor.\n"; var = new int; *var = i; } myclass(const myclass &obj) { cout << "Konstructor kopii.\n"; var = new int; *var = *obj.var; } ~myclass() { cout << "Destructor.\n"; delete var; } }; myclass f() { myclass ob(5); cout << *ob.var << endl; return ob; } int main() { myclass a(10); cout << *a.var << endl; a = f(); cout << *a.var << endl; return 0; }
"Garbage" is displayed:
Obuchnuy konstructor. 10 Obuchnuy konstructor. 5 Konstructor kopii. Destructor. Destructor. -17891602 Destructor.
Why bother to use it at all if dyn. was the memory cleared by the delete operator just as it would have been cleared without a copy constructor? Only without it, "garbage" will appear when calling the destructor of the object myclass :: ob , and with it when calling the destructor of a temporary object.