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: 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