C++ How do I create a dynamic array of objects inherited from an abstract class?

后端 未结 3 1273
一生所求
一生所求 2020-12-22 02:58

My task specifically states that I have to create a random array of Squares and Triangles, that are inherited from an abstract class Figure, and then I have to print out the

3条回答
  •  一整个雨季
    2020-12-22 03:35

    Firstly main must return int. Then you need to create an array of pointers which will show to abstract class Figure.

    Figure **dyn_arr = new Figure*[size];

    Then if you want to add a new object of the derived class you are adding simply like this.

    dyn_arr[0] = new Triangle(); --> this will create new object which will return the address of that object, and your array is actually array of pointers.

    Finnaly if you want to call the function square from any class you can do that like this.

    dyn_arr[0]->square();

    p.s. If you don't have at least a little experience with pointers this can be confusing.

提交回复
热议问题