Initialization by Constructor

A class object with a constructor must be explicitly initialized or have a default constructor. Explicit initialization using a constructor is the only way, except for aggregate initialization, to initialize nonstatic constant and reference class members.

A class object that has no constructors, no virtual functions, no private or protected members, and no base classes is called an aggregate.

Class objects with constructors can be initialized with a parenthesized expression list. This list is used as an argument list for the call of a constructor that is used to initialize the class. You can also call a constructor with a single initialization value using the = operator. Because this type of expression is an initialization, not an assignment , the assignment operator function, if one exists, is not called. This value is used as a single argument for the call of a constructor. The type of the single argument must match the type of the first argument to the constructor. If the constructor has remaining arguments, these arguments must have default values.

Constructors can initialize their members in two different ways. A constructor can use the arguments passed to it to initialize member variables in the constructor definition:

complx( double r, double i = 0.0) {re = r; im = i;}

Or a constructor can have an initializer list within the definition but prior to the function body:

complx ( double r, double i = 0) : re(r), im(i) { /* ... */ }

Both methods assign the argument values to the appropriate data members of the class. The second method must be used to initialize base classes from within a derived class to initialize constant and reference members and members with constructors.



Constructors and Destructors Overview
Unions


Example of Explicit Initialization by Constructor


Initializing Base Classes and Members
Construction Order of Derived Class Objects
Constructors
Syntax of an Explicit Initializer by Constructor
struct (Structures)