Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: Beginner
Jan 18, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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[] = {
// 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 {
float _x,_y,_z;
// Constructors
Vector3() : _x (0), _y(0), _z(0) {};
Vector3( const float X, const float Y,
         const float Z ) {
        _x = X; _y = Y; _z = Z;
But this won't work...
Vector3 VecList[] = {
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
  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]; // ok
Coord *p = new Coord[10]; // ok
However, even if the class doesn't define a default constructor, as does the following class:
class A
  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
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date