[   ^ to index...   |   <-- previous   |   next -->   ]

More about constructors

A constructor's role is to ensure that initialization and resource acquisition is always performed for instances of its corresponding class.

Resource acquisition

One example of a constructor that acquires a resource is the ifstream constructor you used in homework 1:

ifstream input("input_filename.txt"); char buffer[1024]; input >> buffer;

The ifstream constructor which takes a string will automatically perform the equivalent of the C library's fopen system call, and save the filehandle necessary to perform further reads on this file.

Initializer list syntax

For constructors only, C++ allows a special syntax, called the initializer list syntax, which allows you to initialize members to the desired values. The Car example we just did would probably have its constructor defined as follows:

Car::Car(int initX, int initY) : position(initX, initY), speed(0), gas(INIT_GAS), passengers(0) {}

This invokes the Point constructor which takes two integers. Initializer list syntax is more compact than regular assignment syntax and is favored by experienced C++ programmers (there are other reasons to prefer it as well).

Notice that the double and int types are not classes, but they are allowed to use the constructor-like syntax anyway. Equivalent "constructors" are defined for all the primitive types; you can even invoke these constructors directly outside of initializer lists:

double clam(0.5); // instead of: double squid = 0.5;

Last modified: Wed Jun 28 15:42:24 PDT 2000