A
class constructor is a special kind of function in a class that differs in significant respects from an ordinary function member.
A constructor is called whenever a new instance of the class is defined. It provides the opportunity to initialize the new object as it is created and
to ensure that data members contain valid values.
A class constructor always has the same name as the class. Box(), for example, is a constructor for the Box class.
A constructor does not return a value and therefore has no return type. It is an error to specify a return type for a constructor.
There is no such thing as a class with no constructors. If you do not define a
constructor for a class, the compiler will supply a default constructor.
The Box class really looks like this:
class Box{
private:
double length {1};
double width {1};
double height {1};
public:
// The default constructor that is supplied by the compiler...
Box(){
// Empty body so it does nothing...
}
// Function to calculate the volume of a box
double volume(){
return length*width*height;
}
};
The default constructor has no parameters and its sole purpose is to allow an object to be created. It does nothing
else so the data members will have their default values. If there are no initial values specified for data members, they
will contain junk values. Note that when you do define a constructor, the default constructor is not supplied. There are
circumstances in which you need a constructor with no parameters in addition to a constructor that you define that
has parameters. In this case you must ensure that there is a definition for the no-arg constructor in the class.