The Constructor Initializer

A constructor does not exist simply for cosmetic reasons. It can be used to initialize the member variables of an object. Therefore, a constructor provides a valuable alternative to a method initializer, the type of method we saw earlier.

To use a constructor to initialize the member variables of an object, provide as arguments the necessary variables that you intend to initialize. You do not have to initialize all member variables in the constructor, only those that need to be initialized. In fact, you should initialize only those members that you think the other objects or functions would need to provide when calling this object; this means that your object may have member variables that, either the external objects or functions do not need to modify (or access) or the member variable will be initialized later when called from the needed object or function. To initialize the members of our Brick object, its method constructor would be declared as in the following file:

Listing – Brick Unit – Header File: Bricks.h

Listing – Brick Unit – Source File: Bricks.cpp

Main File: Main.cpp

This would produce the following result:

To safeguard and protect the member variables of an object, we have learned to use set and get methods. If you use set methods to protect the variables of an object, you can conveniently call these methods from the constructor to initialize those member variables. Therefore, a constructor can also be used to call methods that hold the initial values of member variables.

Share
Tweet
Share
Pin