07 - C++ Constructors

In this section of the tutorial, you will learn the following:

  • Constructors
  • Destructors

7.1 C++ Constructors

A constructor is function of a class. You do not need to explicitly call a constructor; it is called automatically when an object of the class. You use constructors to initialize variables of a class. Constructors do not have a return type. In addition, the name of the constructor is the same as that of the class. You use constructors to set the initial value of variables.

You may want to initialize date to certain value, each time you create an object of the date class. You can do this as follows:

#include<iostream.h>
class date
{
    private:
        int dd;
        int mm;
        int yy;
    public:        
    date()        //constructor
    {
            dd=01;
            mm=08;
            yy=79;
    }
    void display()
    {
        cout<<”\n”<<dd<”/”<<mm<<”/”<<yy;
    }
};
void main()
{
    date date1;
    date1.display();
} 

In the date class, we have a constructor that initializes the date to 01/08/79.

In main, when you create the object date1, the compiler automatically calls the date constructor that initializes the variables; dd =01, mm=08 and yy=79. The date1.display() statement, displays this date on screen.

A default constructor does not take any parameters. In the above example, date is a default constructor.

7.1.1 Constructor with Parameters

You want to initialize date with values specified by the user. In this case, you would need to pass the user input to the constructor as its parameters. In the above example, we create an object date1 of the type date with a list of parameters. These parameters are passed to the constructor date (int d, int m, int y), which in turn initializes the variables dd, mm, and yy.

#include <iostream.h>
class date
{
    private:
        int dd;
        int mm;
        int yy;
    public:        
    date( int d, int m, int y)    //constructor with                                     parameters
    {
            dd=01;
            mm=08;
            yy=79;
    }
    void display( )
    {
        cout<<”\n”<<dd<”/”<<mm<<”/”<<yy;
    }
};
void main()
{
    date date1(01,08,79);
    date1.display();
}

Note: The type, number, and sequence of parameters determine the constructors the compiler will invoke.

7.2 C++ Destructors

A destructor de-initializes objects. It has the same name as the class, but has a tilde symbol (~) as its prefix. The compiler calls the destructor implicitly when an object goes out of scope or when you destroy an object using the delete operator. It is good practice to use destructors because they help free up memory space.

Note: A class cannot have more that one destructor.

Like us on Facebook