I have a class as given below, I want to write a copy constructor for the same.
I need to create a deep copy constructor for this. following code is printing x and c properly but value of y here is garbage.
#include "stdafx.h"
#include <string.h>
class MyClass
{
public:
MyClass(int a) : y(a) {
}
MyClass(const MyClass &myClass) : y(myClass.y)
{
x = myClass.x;
c = new char[10];
strcpy(c, myClass.c);
}
int x;
char *c;
int &y;
};
int _tmain(int argc, _TCHAR* argv[])
{
MyClass m1(0);
m1.c = new char[10];
strcpy(m1.c, "gourav");
m1.x = 10;
m1.y = m1.x;
MyClass m2 = m1;
printf("x=%d\nc=%s\ny=%d\n", m2.x, m2.c, m2.y);
return 0;
}
In your code, y is reference.. You’re creating MyClass m1(0), so m1.y points to a temporary variable – 0. You just must not do this.. I don’t know why you y member is reference.. ?? Anyway, if you want this to be that way, do that:
Anyway, this is ugly.. And dangerous, if you don’t know what you’re actually doing.. You should really have a very good reason to do that.
Also, redesign your class, and its members’ names..
So, the problem is NOT in the copy-constructor at all..