Constructor Functions  «Prev  Next»
Lesson 6 An initialization constructor
Objective Use constructor to initialize values of class data members

Automatic Initialization

When an object of type Counter is first created, we want its count to be initialized to 0. After all, most counts start at 0. We could provide a set_count() function to do this and call it with an argument of 0, or we could provide a zero_count() function, which would always set count to 0. However, such functions would need to be executed every time we created a Counter object.
Counter c1; //every time we do this,
c1.zero_count(); //we must do this too

This is mistake prone, because the programmer may forget to initialize the object after creating it. It is more reliable and convenient, especially when there are a great many objects of a given class, to cause each object to initialize itself when it is created.
In the Counter class (from the previous lesson), the constructor Counter() does this. This function is called automatically whenever a new object of type Counter is created. Thus in main() the statement Counter c1, c2; creates two objects of type Counter. As each is created, its constructor, Counter(), is executed. This function sets the count variable to 0.
So the effect of this single statement is to not only create two objects, but also to initialize their count variables to 0.

C++ Initialization Constructor

Use constructor to initialize values of class data members
We will now examine the implementation of a data type mod_int to store numbers that are computed with a modulus.

//Modulo numbers and constructor initialization
class mod_int {
   mod_int(int i) { v = i % modulus; }
   void assign(int i) { v = i % modulus; }
   void  print() const { cout << v << '\t'; }
   const static int modulus;
   int  v;
const int  mod_int::modulus = 60;

The integer v is restricted in value to 0, 1, 2, ... , modulus - 1. It is the programmer's responsibility to enforce this restriction by having all member functions guarantee this behavior.
The member function mod_int::mod_int(int) is a constructor. It does not have a return type. It is invoked when objects of type mod_int are used in a definition and has one argument.
When invoked, it requires an expression that is assignment-compatible with its int parameter. It then creates and initializes the declared object.

Same Name as the Class

There are some unusual aspects of constructor functions. First, it is no accident that they have exactly the same name (Counter in this example) as the class of which they are members. This is one way the compiler knows they are constructors.
Second, no return type is used for constructors.
Why not? Since the constructor is called automatically by the system, there is no program for it to return anything to; a return value would not make sense. This is the second way the compiler knows they are constructors.