devxlogo

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

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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist