dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Initialization of an Array of Classes

Question:
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:
// Constructors
Vector3() : _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?

Answer:
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]; // 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
{
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
DevX Pro
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date