Constructors in C++

A constructor in C++ is a special member function whose task is to initialize the objects of its class. It is special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values of data members of the class.

A constructor is declared and defined as follows:

class integer          //class with a constructor
               int m, n;
               integer();     //constructor declared

integer :: integer()     //constructor defined
          m = 0;
          n = 0;

When a class contains a constructor like the one defined above, it is guaranteed that an object created by the class will be initialized automatically.

For example, the declaration:

integer in1;     //object in1 created

not only creates the object in1 of type integer but also initializes its data members m and n to zero. There is no need to write any statement to invoke the constructor function (as we do with the normal member functions). If a normal member function is defined for zero initialization, we would need to invoke this function for each of the object separately. This would be very inconvenient, if there are a large number of objects.

The constructor functions in C++ have some special characteristics as stated below:

  1. They should be declared in the public section
  2. They are invoked automatically when the objects are created
  3. They do not have return types, not even void and therefore, they cannot return values
  4. They cannot be inherited, though derived class can call the base class constructor (The topics of inheritance, derived class and base class would be covered later)
  5. Like other C++ functions, they can have default arguments
  6. Constructors cannot be virtual (Meaning of virtual would be discussed later)
  7. We cannot refer to their addresses

Remember, when a constructor is declared for a class, initialization of the class objects becomes mandatory.

You may also like...

2 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *