Learn C++ - C++ Constructor






A class constructor is a special kind of function in a class.

A constructor is called when a new instance of the class is defined.

It initializes the new object as it is created and ensures that data members contain valid values.

A class constructor 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.

If you don't define a constructor for a class, the compiler will supply a default constructor.

Object Initialization with new

In general, if Class_name is a class and if value is of type Type_name, the statement

Class_name * pclass = new Class_name (value);

invokes this constructor:

Class_name (Type_name);

There may be trivial conversions, such as to this:

Class_name(const Type_name &);




Example

Instantiating multiple objects of the MyBook class and using the MyBook constructor to specify the course name when each MyBook object is created.


#include <iostream> 
#include <string>
using namespace std; 
/*from w w w  .  j a va  2 s . c o  m*/
class MyBook { 
public: 
    // constructor initializes courseName with string supplied as argument 
    MyBook( string name ) { 
       setCourseName( name ); // call set function to initialize courseName 
    }

    // function to set the course name 
    void setCourseName( string name ) 
    { 
       courseName = name; // store the course name in the object 
    }

    // function to get the course name 
    string getCourseName() 
    { 
       return courseName; // return object's courseName 
    }

    // display a welcome message to the MyBook user 
    void displayMessage() 
    { 
       // call getCourseName to get the courseName 
       cout << "Welcome to the grade book for\n" << getCourseName() 
           << "!" << endl; 
    }
private: 
    string courseName; // course name for this MyBook 
};

int main() { 
    // create two MyBook objects 
    MyBook MyBook1( "C++ Programming" ); 
    MyBook MyBook2( "C++" ); 

    // display initial value of courseName for each MyBook 
    cout << "MyBook1 created for course: " << MyBook1.getCourseName() 
        << "\nMyBook2 created for course: " << MyBook2.getCourseName() 
        << endl; 
}

The code above generates the following result.





Copy Constructor

The form of the copy constructor is the same for any class:

    
Type::Type(const Type& object) 
{ 
  // Code to duplicate of object... 
} 

Example 2

The default constructor has no parameters and its sole purpose is to allow an object to be created.

  
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; 
  } 
}; 

Example 3

The following code adds constructor to Box class.


#include <iostream> 
  /*from w ww .  ja  v  a2 s .c o  m*/
// Class to represent a box 
class Box { 
private: 
  double length {1.0}; 
  double width {1.0}; 
  double height {1.0}; 
  
public: 
  // Constructor 
  Box(double lengthValue, double widthValue, double heightValue) 
  { 
    std::cout << "Box constructor called." << std::endl; 
    length = lengthValue; 
    width = widthValue; 
    height = heightValue; 
  } 
  
  // Function to calculate the volume of a box 
  double volume() 
  { 
    return length*width*height; 
  } 
}; 
  
int main() 
{ 
  Box firstBox {80.0, 50.0, 40.0};               // Create a box 
  double firstBoxVolume {firstBox.volume()};     // Calculate the box volume 
  std::cout << "Volume of Box object is" << firstBoxVolume << std::endl; 
} 

The code above generates the following result.

Defining Constructors Outside the Class

The definition of a function member can be placed outside the class definition.

This is also true for class constructors.


#include <iostream> 
class Box { //ww  w  .ja v  a 2 s .c o  m
private: 
  double length {1.0}; 
  double width {1.0}; 
  double height {1.0}; 
  
public: 
  // Constructors 
  Box(double lengthValue, double widthValue, double heightValue); 
  Box();                                    // No-arg constructor 
  double volume();                          // Function to calculate the volume of a box 
}; 
// Constructor definition 
Box::Box(double lengthValue, double widthValue, double heightValue) 
{ 
  std::cout << "Box constructor called." << std::endl; 
  length = lengthValue; 
  width = widthValue; 
  height = heightValue; 
} 
  
Box::Box() {}                                    // No-arg constructor 
// Function to calculate the volume of a box 
double Box::volume() 
{ 
  return length*width*height; 
} 
 
int main() 
{ 
  Box firstBox {80.0, 50.0, 40.0};              // Create a box 
  double firstBoxVolume{firstBox.volume()};     // Calculate the box volume 
  std::cout << "Volume of Box object is" << firstBoxVolume << std::endl; 
} 

The code above generates the following result.

Default Constructor Parameter Values

class Box { 
private: 
  double length; 
  double width; 
  double height; 
  
public: 
  // Constructors 
  Box(double lv = 1.0, double wv = 1.0, double hv = 1.0); 
  Box();                                            // No-arg constructor 
  double volume();                                  // Function to calculate the volume of a box 
};