array of objects

I have a the following classes:
parent classed called "CPolygon"
and its child class called "CTriangle" and "CRectangle"

In the main function how do I create an ARRAY of class 'CPolygon' dynamically and when the user says he wants to create a new Triangle, the CPoly[i] will become a new Triangle object and so goes for creating a Rectangle object.
I cannot use vector for this.
I read the documentation file and other forums.

Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
using namespace std;

class CPolygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area (void) =0;
    void printarea (void)
      { cout << this->area() << endl; }
  };

class CRectangle: public CPolygon {
  public:
    int area (void)
      { return (width * height); }
  };

class CTriangle: public CPolygon {
  public:
    int area (void)
      { return (width * height / 2); }
  };

int main () {
  
  //create an array of CPolygon objects called OPoly[] that will be dynamically 
  //increased as the user enters new entries

  int choice;
  while(1){
  cout<< "1: Trianlge\n2: Rectangle"<<endl;
  cin<<choice;

  if(choice==1)
  {
     //make this object of CPolygon array, an object of CTriangle
     //do some work here related to CTraingle
  }
  else
  {
     //make this object of CPolygon array, an object of CRectangle
     //do some work here related to CRectangle
  }
  //increase array OPoly here
  }
}
Last edited on
CPolygon *p can point to all children classes, so in this case:

p = new CRectangle();
or
p = new CTriangle();

For array which you want just create array of CPolygon pointers:
1
2
3
int size;
cin >> size;
CPolygon  **p;


p = new CPolygon *[size];
and now fill the array however you want:
1
2
p[0] = new CRectangle();
p[1] = new CTriangle();


and use like:
p[0]->set_values (2,2);

and obviously dont forget to clean the memory after you are done
Last edited on
Thank you so much tath!!
But still, one problem remains unsolved for me... How to increase the array size dynamically without "cin>>size"... like everytime the it comes to the end of the while loop in my previous code, can't I increase the size of the array by 1 so that another CPolygon can be made... without using vectors

Thanks again.
Last edited on
surely this doesnt require the use of maloc or realloc??
You can also create simple Linked List class.
I saw a method of the object array being copied to another array of objects with one object more, then the previous one getting deleted.
Is this also correct?

Thank you tath
Thank you all, specially tath for answering my query.
I have finally finished the program I wanted thanks to you all :)
No problem :). Just select this topic as Solved.
Topic archived. No new replies allowed.