ozdm
ozdm

Reputation: 153

Defining the size of a vector inside a class in C++

I have a class named "Circle" which is defined by the number of points on its circumference. Each point, in turn, is defined by its x and y value. In order to create individual points, I have a class like this:

class Point{
public:
    double x; // x position
    double y; // y position

    // Default constructor
    Point()
    : x(0.0),y(0.0){
    }
};

which basically creates a point. I create the "Circle" from these points by way of this class:

class Circle{
public:
    vector<Point> points; // points with x and y coordinates

    // Default constructor
    Circle()
    : points(0.0) {
    }
};

which creates the circle as a combination of points.

The number of circles and the corresponding points on each of them are already pre-determined. Let's say there are M circles and N points on each of them, for the sake of argument. So I create these entities like this:

vector<Circle> circles(M);

and this is where my problem begins, because I want to pre-determine the size of the vector "points" for each of my "circles" objects like:

vector<Point> points(N);

tl;dr How can I define the size of a vector inside of a class? It really doesn't matter whether I do it from inside of the class or not. All I want is to be able to determine the size of "points" vector for each "circles" object to N.

Upvotes: 1

Views: 836

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310970

Define the constructor of class Circle with a parameter

class Circle{
public:
    vector<Point> points; // points with x and y coordinates

    // Default constructor
    Circle( size_t n ) : points( n ) 
    {
    }
};

And then declare the vector of Circle

vector<Circle> circles( M, N );

If you want that the constructor would be explicit as for example

explicit Circle( size_t n ) : points( n ) 
{
}

then you have to define the vector the following way

vector<Circle> circles( M, Circle( N ) );

Also you can make the constructor default

    Circle( size_t n = 0 ) : points( n ) 
    {
    }

Upvotes: 3

Related Questions