Please explain the mechanics of how it works.

class Parent { protected: int parentInt; public: void printInt() {std::cout << parentInt;} }; class Child : public Parent { private: int childInt; public: void printInt() { Parent::printInt(); std::cout << parentInt; } }; Parent* = kids[10]; kids[0] = new Child; 

I created an array of pointers of the parent type, but when I create an object of a child class, can I still put it in an array of pointers to the parent type? How it works?

That is, when creating an object, I am allocated so much memory that all my variables and methods fit there. In the successor, I, it turns out, add some more variables, that is, the object itself takes up more memory, but I can still access the pointer to the parent type, which, it seems, is smaller. I hope, clearly stated the idea. I myself do not understand well. :)

  • P - polymorphism - raviga
  • I want to understand, this is some kind of backstage magic that the compiler casts, or there is some kind of transparent mechanism that in runtime understands that it is the heir of the parent, and therefore I will highlight here another 4, 8, 100 bytes more, simply because the secondary ? - Alex Sazonov

1 answer 1

"when creating an object of a child class, I can still put it in an array of pointers to the parent type" - no, you can not. In the example, you convert the pointer to the child type to the pointer to the parent type and put it into an array of pointers to the parent type.

"when creating an object, I am allocated so much memory so that all my variables and methods fit there" - no, the methods of objects are never stored in it.

  • But where am I transforming something? I definitely say in that code kids[0] = new Child; where kids[0] is a pointer to the parent type, and I put there already the heir. Or where does the conversion take place? - Alex Sazonov
  • @AlexSazonov In this line it happens. kids[0] = new Child is like Parent* p = new Child - vegorov
  • @AlexSazonov You are not placing Child heir there, but a pointer to Child * heir. Such a pointer can be implicitly converted to a pointer to the parent class Parent * because inheritance is an "is" relationship - VTT
  • So this happens behind the scenes and is done automatically by the compiler? Based on the fact that these two classes have a connection Parent -> Heir? - Alex Sazonov
  • one
    @AlexSazonov Yes, but you can also make it explicitly kids[0] = static_cast<Parent *>(new Child); - VTT