Tell me how in C ++ you can allocate memory for an array of classes, so that each element can be determined not only by the type of this class, but also the type of heirs of the original class. Those. There is for example a class cClassParent and two classes of the successor cClassChild1 and cClassChild2. How to allocate memory for an array of cClassParent, so that the i-th element of the array could be redefined as cClassChildN tried, for example

cClassParent* obj = new cClassParent[3]; obj[2] = cClassChild1(); 

does not work

    1 answer 1

    Through an array of pointers to the base class.

     Parent** array = new Parent* [20]; array[0] = new Parent; array[1] = new Child; 

    But then read about virtual members (very well written in Myers Effective Programming). In general, basic rules 2:

    1. Always make the base class destructor virtual.
    2. All methods that you plan to override, make virtual.

    Item 1 is needed to prevent any troubles, and item 2 to provide access to the methods of the derived class through a pointer to the base class.