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

Consider the following class:

   class A  // lacks default constructor  {  public:     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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: