0

How do copy constructors work ??

steps to execute or call !!

19th Oct 2017, 1:50 PM
Kashish Sahu
Kashish Sahu - avatar
1 Réponse
+ 2
The copy constructor takes its own class as parameter. If you have a class T, the parameters can be 1 of the following T&, const T&, volatile T&, or const volatile T&. Notice that you the parameter must always be passed as reference. Inside the copy contructor you would copy over all the member variables. Example, For simplicity I'll just put everything under public. class T { public: T( int n ):n(n){} // Constructor taking an int T( const T& a ) // Copy constructor { n = a.n; } int n; }; Inside main you can now use it like this: T a1(5); // Initialize a1 through the constructor taking the int T a2(a1); // Initialize a2 through the copy constructor There is 1 major pitfall that you must burn into your brain. What if the class has a dynamically allocated member variable? ( called through new ) If you just copy it, or if you don't have a copy constructor at all it will create a shallow copy, meaning you now have 2 pointers pointing to the same address. What happens when the destructor is called to delete 1 of them? The other is left with a pointer to unallocated memory. and when the 2nd destructor is called? It will try to delete it again, resulting in memory corruption followed by a crash. Oh what to do now? :( Simple! You allocate inside the copy constructor so they point to different memory regions! Example: class T { public: T( int n ):n(new int(n)){} // Constructor taking an int as argument T( const T& a ) // copy constructor { n = new int(*a.n); // Allocate memory for n and assign it the value whatever a.n is pointing to } ~T(){ delete n; } // Destructor, never forget deletion int* n; }; T b1(6); T b2(b1); cout << b1.n << " " << b2.n; // You can see the addresses are different :) When we talk about the copy assignment operator, they are similar but there are some more things to watch out for. But that's for another time.
19th Oct 2017, 2:58 PM
Dennis
Dennis - avatar