Browse DevX
Sign up for e-mail newsletters from DevX

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



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

Creating an Array of Objects in the Absence of a Default Constructor

Consider the following class:

  class A  // lacks default constructor
    A(int x, int y); 

Class A doesn't have a default constructor. Therefore, the following array declaration will not compile:

  A arr[10]; //error; no default constructor for class A

You can still create arrays of class A. However, you'll have to use an explicit initialization list in this case:

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

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. Furthermore, you cannot create dynamic arrays of objects of a class that lacks a default constructor:

  A * pa = new A[2]; // error

Therefore, if you define a constructor for a class, remember to define a default constructor as well.

Danny Kalev
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