A constructor is a code segment that is invoked automatically whenever you instantiate an instance of a class. All non-primitive objects have at least one constructor but class designers can create as many constructors as required, giving consumers the freedom to construct objects more efficiently. If you don't declare any constructors, the compiler will generate both a default constructor (one that has no arguments) and a copy constructor for you.
The purpose of a constructor is simply to initialise the class member variables. This is usually done via the class constructor initialisation list. Constructors also have a body (much like a function) which can be used to call methods of the class to perform more complex initialisations. However the initialisation list is the most efficient method, as it is not unlike initialising a primitive variable at the point of instantiation, rather than instantiating and initialising variables in two stages as you would with C.
Constructors are also subject to access specifiers, but will usually be declared public unless the class is an abstract base class in which case they may be declared protected. Private access is typically used when declaring singleton classes (where construction is achieved via a static member method that instantiates the one and only instance of the class, which is itself declared a static member variable of the class).
Note that copy constructors are invoked automatically whenever you pass objects to functions by value. Copying a derived object automatically invokes its base class copy constructors, while copying containers automatically invokes the embedded object copy constructors. This is why pass by reference (or via pointer) is the preferred method of passing objects into functions, as there is no need to reconstruct the object being passed.
Chat with our AI personalities