Constructor

In class-based object-oriented programming, a constructor is a special type of subroutine called to create an object.

Is a special kind of method that specifies one possible construction recipe for a new instance of the class.

In C++

This is how a object is actually created:

  1. Space is allocated
  2. Call the superclass constructor
  3. Initialize fields via a member initialization list (MIL)
  4. Run the constructor body

Compiler-Provided Constructor

If you do not write any constructors at all, you get a compiler provided default constuctor:

  • Primitive fields are uninitialized (garbage values)
  • Object fields are default constructed

If you write any constructor yourself, the compiler provided constructor is not supplied.

The constructor has the same name as the Class name.

Always USE MIL

Why?:

  • For four reasons mentioned in CS247.