Class array with variable number of elements

closed account (DL30RXSz)
I'm creating a class which represents a polygon, and I want it to be able to set the number of sides when constructed so I wrote this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Polygon
{
public:
	Polygon(int initNumOfSides){ numOfSides = initNumOfSides; }
	~Polygon(){ ;}

	void SetSide(int side, double value);
	double GetSide(int side);
private:
	int numOfSides;
	double sides[numOfSides]; /* line 37 */
	double height;
};

void Polygon::SetSide(int side, double value)
{
	sides[side-1] = value;
}

double Polygon::GetSide(int side)
{
	return sides[side-1];
}

This gives me two errors.
error C2327: 'Polygon::numOfSides' : is not a type name, static, or enumerator
error C2065: 'numOfSides' : undeclared identifier

How should I do this?
Last edited on
That's not how you make a dynamic array. You would need to use new in your constructor and delete in the destructor. Look here for more info: http://www.cplusplus.com/doc/tutorial/dynamic/

You could also use a vector and set it's size when you construct your own object so you don't have to worry about deleting it.
closed account (DL30RXSz)
Thank you, that works much better. Here is my new code:
1
2
3
4
5
6
7
8
9
10
11
12
class Polygon
{
public:
	Polygon(int initNumOfSides){ sides = new (nothrow) double[initNumOfSides]; }
	~Polygon(){ ;}

	void SetSide(int side, double value);
	double GetSide(int side);
private:
	double* sides;
	double height;
};

Will the array be deleted automatically when the destructor is run? If not, can I tell it to do so int the destructor's definition?
Will the array be deleted automatically when the destructor is run?


No

If not, can I tell it to do so int the destructor's definition?


Yes:

 
~Polygon(){ delete[] sides; }


Also note that you should probably make a copy constructor and assignment operator too, otherwise you'll have problems if you copy Polygons.
Topic archived. No new replies allowed.