I have a parent-child inheritance structure. I have an object that was instantiated(new) by parent class. I want to downcast this object to child class. I need a automatic routine like casting because parent class has a lot of properties and copying parent properties in child object is impossible.
I can cast parent object to child object with reinterpret_cast operator so that I have parent properties values in my child object but I encountered with other problem.
After downcasting if you assign memory to one of child specific variables , when you want to delete child object you will faced with memory segmentation fault error. it seems heap was corrupted.
my code is similar to this :
class parentclass
{
public:
int parent_var = 10;
parentclass()
{
parent_var = 20;
}
};
class childclass :parentclass
{
public:
int* child_var;
childclass()
{
child_var = NULL;
}
};
void main()
{
parentclass* pobj = new parentclass();
childclass* cobj;
cobj = reinterpret_cast<childclass*>(pobj);
//everything is ok, cobj.parent_var has correct value (=20)
//and child specific variables are filled with random variables.
delete cobj;
// cobj delete successfully
parentclass* pobj2 = new parentclass();
childclass* cobj2;
cobj2 = reinterpret_cast<childclass*>(pobj2);
//everything is ok and
//cobj2.parent_var has correct value
cobj2->child_var = new int[10]; // assign memory to child specific variable
delete cobj2; // Here Heap corruption Error occurred.
}
I read similar pages in stackoverflow but most of them describe casting when object new with childclass. your helps are appreciated.