Constructor Functions  «Prev 

C++ Constructor and Destructor Example

Constructors are for initialization. In the debugging and prototyping phase of code development, it is also useful to add code to constructors that outputs or tests behavior. However, once the debugging and prototyping phase is complete, any other work besides initialization should not be carried out by a constructor.
For example, if in initializing an integer variable the system printed out its square root and whether it was prime, we would be properly upset.
Similarly, destructors are for deallocation and finalization. Other uses of destructors should be avoided. Destructors should retrieve resources connected with the variables going out of scope. They are conceptually the inverse computation to a corresponding constructor.

A constructor is a special kind of class member function that is executed when an object of that class is instantiated. Constructors are typically used to initialize member variables of the class to appropriate default values, or to allow the user to easily initialize those member variables to whatever values are desired.
Unlike normal functions, constructors have specific rules for how they must be named:
  1. Constructors should always have the same name as the class (with the same capitalization)
  2. Constructors have no return type (not even void)

C++ also includes the ability to define a structure that is similar to a class and defines a type. The structure originated in C. You define a structure in essentially the same way as a class but using the struct keyword instead of the class keyword. In contrast to members of a class, the members of a structure are public by default.
Structures are still used frequently in C++ programs to define types that represent simple aggregates of several variables of different types, the margin sizes and dimensions of a printed page for example. I will not discuss structures as a separate topic because aside from the default access specification and the use of the struct keyword, you define a structure in exactly the same way as a class.