Initialization of an Array of Classes

A common practice in C is to do something like this to initialize an array of structs:

typedef struct {float x,y,z;} Vector3;Vector3 VecList[] = {{1,0,0},{0,1,0},{0,0,1}};// Now VecList[0] = {1,0,0};//     VecList[1] = {0,1,0}; etc...

Now, I would like to do the same for a class in C++:

class Vector3 {private:float _x,_y,_z;public:// ConstructorsVector3() : _x (0), _y(0), _z(0) {};Vector3( const float X, const float Y,         const float Z ) {        _x = X; _y = Y; _z = Z;};~Vector3();};

But this won’t work…

Vector3 VecList[] = {{1,0,0},{0,1,0},{0,0,1}};

I assume there’s a way… so how can I do this?

This question exemplifies the importance of declaring a default constructor in a class. Please note that a default constructor is one that can be called without any arguments; it isn’t necessarily a constructor that takes no arguments. Thus, even if the class’s constructor takes one or more parameters, it’s advisable to give these parameters default values:

class Coord{public:  Coord(int x = 0, int y = 0);};

The default parameter values enable you to use the class in a context that requires a default constructor, for example, when declaring arrays:

Coord carr[10]; // okCoord *p = new Coord[10]; // ok

However, even if the class doesn’t define a default constructor, as does the following class:

class A{public:   A(int n); //no default constructor};

you can still create arrays, although you need to use an explicit initialization list this time:

A a[3] = { A(0), A(0), A(0)};

Note that in the declaration of the array a, every element must be explicitly initialized. This is tedious, especially if you create a large array. Worse yet, you cannot create dynamic arrays of objects of a class that lacks a default constructor:

A * pa = new A[2]; //error; A has no default ctor
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: