mercredi 17 mars 2021

Saving copy of child class inside parent C++ (not pointer) (Polymorphic)

How can I store child class copy inside a parent class object? As you can see in my code I have a parent class and a child class with "int a" value. I would like to change this value and store it inside a parent class object. As you can see I changed this int value to 4. How can I store this with parent class object? Is this even possible? Or should I use dynamic memory allocation and pointers?

class Parent {
public:
  void sleep() {}
};

class Child: public Parent {
public:
  void gotoSchool(){}
  int a;
};

struct MyStr{
    Parent parent;
};

int main( ) 
{ 
  Parent parent;
  Child child;

  std::cout<<  child.a <<std::endl;

  Parent *pParent = &child; 

  Child *pChild =  (Child *) pParent;
  
  std::cout<<  pChild->a <<std::endl;
  pChild->a =4;
  
  MyStr myStr;
  myStr.parent = *pChild;

  std::cout<<   ((Child*)( &myStr.parent))->a <<std::endl;   


  return 0; 
}

As you can see in my last cout, I tried to print integer a value which should be 4 but it is undefined behavior. I want it to be 4. Is there a way?

Aucun commentaire:

Enregistrer un commentaire