1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Tutorial - Copy Constructors

By , About.com Guide

3 of 10

Initializing an Array with a Default Constructor

Constructors and Arrays

If you have an array of objects, the only constructor that can be called on each object is the default constructor. You cannot use a non default constructor to construct arrays of objects. So if we reuse the phonerec declaration from the previous page:

phonerec() : name("Me"),phonenunber("555-1000") {}
and declare an array of three phonerecs,
phonerec subscribers[3];
then this will call the default constructor three times, once on each object and set the name field of each to "Me" etc.

The example below uses an initializer list that constructs each object in an array of 10 objects, and calls a function to set each object to have a different id value. After the array has been constructed, A[0]has an id of 0, A[1] an id of 1 etc.

#include <string>

using namespace std;

int x=0;
int getX() {
    return x++;
}

class a {
  public:

   int b;
    int id;
    string s;
    
    a() : id(getX()), b(5), s("value2") { }
    
};

void main() {
    a A[10];
}

a A[10];
This can also be done by using a static data member of a class. We'll see those in a future lesson.

On the next page Creating and Using Copy Constructors

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Initializing an Array with a Default Constructor

©2009 About.com, a part of The New York Times Company.

All rights reserved.