Constructors

A constructor is a member function with the same name as its class. For example:

class X
{
public:
      X();      // constructor for class X
};

Constructors are used to create, and can initialize, objects of their class type.

A default constructor is a constructor that either has no arguments, or, if it has arguments, all the arguments have default values. If no user-defined constructor exists for a class and one is needed, the compiler creates a default constructor, with public access, for that class. No default constructor is created for a class that has any constant or reference type members.

Like all functions , a constructor can have default arguments. They are used to initialize member objects. If default values are supplied, the trailing arguments can be omitted in the expression list of the constructor. Note that if a constructor has any arguments that do not have default values, it is not a default constructor.

A copy constructor is used to make a copy of one class object from another class object of the same class type. A copy constructor is called with a single argument that is a reference to its own class type. You cannot use a copy constructor with an argument of the same type as its class; you must use a reference. You can provide copy constructors with additional default arguments. If a user-defined copy constructor does not exist for a class and one is needed, the compiler creates a copy constructor, with public access, for that class. It is not created for a class if any of its members or base classes have an inaccessible copy constructor.

If a class has a base class or members with constructors when it is constructed, the constructor for the base class is called, followed by any constructors for members. The constructor for the derived class is called last. Virtual base classes are constructed before nonvirtual base classes. When more than one base class exists, the base class constructors are called in the order that their classes appear in the base list.

You cannot call constructors directly. You use a function style cast to explicitly construct an object of the specified type.



References
Constructors and Destructors Overview


Construction Order of Derived Class Objects
Destructors
Construction Order of Derived Class Objects
Default Arguments in C++ Functions


Examples of Constructors and Construction Order
Example of Explicitly Constructing an Object