I am not able to understand this behavior. I have a class A,
class A
{
public:
int ch;
char *s;
A()
{}
A(char *st):ch(0)
{
s = new char[10];
strcpy(s,st);
}
A(const A& rhs):ch(rhs.ch)
{
s = new char[strlen(rhs.s)+1];
strcpy(s,rhs.s);
}
const A& operator=(const A& rhs)
{
char *temp = new char[strlen(rhs.s)+1];
strcpy(temp,rhs.s);
delete[] s;
s=temp;
ch = rhs.ch;
return *this;
}
~A()
{
delete []s;
}
};
Till this point everything goes as expected I am able to test my copy constructor and assignment operator and they are working properly.
Now I created a child class B and I am getting heap corruption error. I am not able to understand, is this the problem related somewhere with class A destructor. ?
Below is my class B,
class B:public A
{
public:
int a;
B():a(0){}
};
You default constructor for
Adoes not initialise the members(a pointer):Hence when elements are constructed using this constructor, you get a crash when the destructor deletes the uninitialized element:
Class
Buses the default constructor forA, and therefore triggers this problem. Avoid it by properly initializing all members in the default constructor: