Lessons Home

Object Construction and Destruction

 

Constructors

 

Method Initializer

In order to further customize the behavior of an object, you should make sure that it completely controls its member variables. An object should "know" what kind of values its variables hold and what values are not acceptable. As a starting point, when calling an object from another function, you should know what value a particular member is holding, before performing any operation. To solve this problem, one solution is to provide a special function that would initialize the member variables.

A method that initializes can return any value but it is preferable to return a void because its primary purpose is to reset the values. Since this method would give a starting value to all member variables that need to be initialized, it should have an equivalent argument for each of the member variables that it would initialize.

Consider an object used to handle a brick; a rectangular parallelepiped is recognized by its length, height, and width. A method used to initialize its dimensions would look like this:

//---------------------------------------------------------------------------

#include <iostream> 

using namespace std;

struct TBrick

{

public:

    void Initializer(double l, double h, double w);

    double Volume() const;

    void Properties() const;

private:

    double Length;

    double Height;

    double Width;

};

//---------------------------------------------------------------------------

void TBrick::Initializer(double l, double h, double w)

{

    Length = l;

    Height = h;

    Width = w;

}

//---------------------------------------------------------------------------

double TBrick::Volume() const

{

    return Length * Height * Width;

}

//---------------------------------------------------------------------------

void  TBrick::Properties() const

{

    cout << "Red Brick Properties";

    cout << setiosflags(ios::fixed) << setprecision(2);

    cout << "\nLength = " << Length;

    cout << "\nHeight = " << Height;

    cout << "\nThickness = " << Width;

    cout << "\nVolume = " << Volume() << "\n";

}

//---------------------------------------------------------------------------

int main()

{

    TBrick RedBrick;



    RedBrick.Initializer(124.45, 56.25, 32.55);

    RedBrick.Properties();

    

    return 0;

}

//---------------------------------------------------------------------------

This would produce:

Red Brick Properties

Length = 124.45

Height = 56.25

Thickness = 32.55

Volume = 227860.17



Press any key to continue...

Once declared and implemented, a method initializer can be used as the "entry point" to the object; for example, it can be used to pass values from the external world to the member variables of an object. In the following example, the user supplies the dimensions of the brick. Since the dimensions are held by private members, their values will be carried from the outside by the method used to initialize:

//---------------------------------------------------------------------------

int main()

{

    double length, height, width;

    TBrick GoneSand;



    cout << "Before building this brick, provide its dimensions\n";

    cout << "Length: ";

    cin >> length;

    cout << "Height: ";

    cin >> height;

    cout << "Width:  ";

    cin >> width;

    cout << endl;



    GoneSand.Initializer(length, height, width);

    GoneSand.Properties();



    

    

    return 0;

}

//---------------------------------------------------------------------------

An example of running the program would produce: 

Before building this brick, provide its dimensions

Length: 8.95

Height: 6.85

Width:  6.25



Red Brick Properties

Length    = 8.95

Height    = 6.85

Thickness = 6.25

Volume    = 383.17



Press any key to continue...
  

Initializing an Object

  1. To create a new project, on the main menu, click File -> New or File -> New -> Other...
  2. On the New Items dialog box, double-click Console Wizard.
  3. On the Console Wizard dialog box, make sure the C++ radio button is selected. In the right section, click only the Console Application check box and click OK.
  4. To save the project, on the Standard toolbar, click the Save All button.
  5. Click the Create New Folder button, type Students2 and press Enter twice to put the new folder name in the Save In combo box.
  6. Change the File Name content to Main and press Enter.
  7. For the name of the project, type Student and press Enter.
  8. To add a new unit, on the main menu, click File -> New or File -> New -> Other...
  9. In the New Items dialog box, double-click Unit.
  10. To save the unit, on the Standard toolbar, click the Save button.
  11. Type Students as the unit name and press Enter.
  12. Click the Students.h tab and change its content as follows:
     
    //---------------------------------------------------------------------------
    
    #ifndef StudentsH
    
    #define StudentsH
    
    #include <string>
    
    using namespace std;
    
    //---------------------------------------------------------------------------
    
    class TStudent
    
    {
    
    public:
    
        void  InitialValues(string fn, string ln,
    
                                     int DOB, int MOB, int YOB);
    
        void  Display();
    
    private:
    
        string FirstName;
    
        string LastName;
    
        int DayOfBirth;
    
        int MonthOfBirth;
    
        int YearOfBirth;
    
    };
    
    //---------------------------------------------------------------------------
    
    #endif
  13. Click the Students.cpp file and change it as follows:
     
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    void  TStudent::InitialValues(string fn, string ln,
    
                                     int DOB, int MOB, int YOB)
    
    {
    
        FirstName    = fn;
    
        LastName     = ln;
    
        DayOfBirth   = DOB;
    
        MonthOfBirth = MOB;
    
        YearOfBirth  = YOB;
    
    }
    
    //---------------------------------------------------------------------------
    
    void  TStudent::Display()
    
    {
    
        // Display the characteristics of the student
    
        cout << "Characteristics of this student";
    
        cout << "\nFull Name: " << FirstName << " " << LastName;
    
        cout << "\nDate of Birth: " << DayOfBirth
    
             << "/" << MonthOfBirth << "/" << YearOfBirth << "\n";
    
    }
    
    //---------------------------------------------------------------------------

  14. Click the Main.cpp file and change it as follows:
     
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    void  Exit()
    
    {
    
        cout << "\n\nPress any key to continue...";
    
        
    
    }
    
    //---------------------------------------------------------------------------
    
    int main()
    
    {
    
        TStudent FirstGrade;
    
    
    
        FirstGrade.InitialValues("Jules", "Senga", 1, 1, 1990);
    
        FirstGrade.Display();
    
    
    
        Exit();
    
        return 0;
    
    }
    
    //---------------------------------------------------------------------------

  15. Press F9 to test the program.

Default Constructor

As we have already seen, an object combines methods and variables grouped to accomplish a particular purpose. A constructor is a special method that is created when the object is created or defined. This particular method holds the same name as that of the object and it initializes the instance of the object whenever that object is created. The constructor also usually holds the initializations of the different declared member variables of its object. Unlike some of the other methods, the constructor does not return a value, not even void.

When you create an object, if you do not declare a constructor, the compiler would create one for your program; this is useful because it lets all other objects and functions of the program know that this object exists. This compiler created constructor is called the default constructor. If you want to declare your own constructor, simply add a method with the same name as the object in the public section of the object. When you declare an instance of an object, whether you use that object or not, a constructor for the object is created and signals itself.

A constructor is declared without a return value, that also excludes void. Therefore, when implemented, do not return a value:

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;

//---------------------------------------------------------------------------



struct TBook

{

public:

    TBook();    // Constructor

};

//---------------------------------------------------------------------------

TBook::TBook()

{

    cout << "I see a book...\n";

}

//---------------------------------------------------------------------------

int main()

{

    TBook B;



    return 0;

}

//---------------------------------------------------------------------------

This would produce:

I see a book...

This book constructor is a programmer created constructor and is empty. You might find it sometimes convenient to create your own constructor because, whether you create an empty constructor or not, this does not negatively impact your program but makes it more lively and allows other parts of the program to conveniently call the object using its constructor. A constructor is easily implemented once you have created one:

There are various categories of bricks used in the construction industry.

For this exercise, we will consider a simple one used in constructing domestic building foundations. It has a total length, here called Length; it also has a height, referred here to as Height; and it has a thickness that will be called Thickness. For resistance and static reasons, our brick will have two holes. Since we are more interested in the amount of cement used to create the brick, we will subtract the volume of the hole from the total volume. The dimensions we use are for simplicity. We will consider that the small wall of the brick has a thickness of 0.25; also, the static wall in the middle length has a thickness of 0.25.

Listing - Brick Unit - Header File: Bricks.h

//---------------------------------------------------------------------------

#ifndef BricksH

#define BricksH



//---------------------------------------------------------------------------

struct TBrick

{

public:

     TBrick(); // Empty Constructor

    void  setDimensions(double l, double h, double t);

    void  Initializer(double l, double h, double w);

    double  CementVolume();

    void  ShowProperties();

private:

    double Length;

    double Height;

    double Thickness;

};

//---------------------------------------------------------------------------

#endif

Brick Unit - Source File: Bricks.cpp

//---------------------------------------------------------------------------

#include <iostream>

#include <iomanip>

using namespace std;



#include "Bricks.h"



//---------------------------------------------------------------------------





//---------------------------------------------------------------------------

 TBrick::TBrick()

{

    //TODO: Add your source code here

}

//---------------------------------------------------------------------------

void  TBrick::setDimensions(double l, double h, double t)

{

    Length = l;

    Height = h;

    Thickness = t;

}

//---------------------------------------------------------------------------

double  TBrick::CementVolume()

{

    double Enclosure = 0.50; // This includes both walls of the brick itself

    double HoleLength = Length - 0.75; // Including both holes

    double HoleThickness = Thickness - Enclosure;

    double HoleVolume = HoleLength * HoleThickness * Height;

    double TotalVolume = Length * Height * Thickness;

    double ValidVolume = TotalVolume - HoleVolume;



    return ValidVolume;

}

//---------------------------------------------------------------------------

void  TBrick::ShowProperties()

{

    cout << "Foundation Brick Properties";

    cout << setiosflags(ios::fixed) << setprecision(2);

    cout << "\nLength    = " << Length; cout

         << "\nHeight    = " << Height;

    cout << "\nThickness = " << Thickness;

    cout << "\nCement Volume = " << CementVolume() << "\n";

}//---------------------------------------------------------------------------

Main File: Main.cpp

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;

#include "Bricks.h"

//---------------------------------------------------------------------------



//---------------------------------------------------------------------------

int main()

{

    TBrick Foundation;



    Foundation.setDimensions(4.24, 3.55, 3.45);

    Foundation.ShowProperties();



    

    

    return 0;

}

//---------------------------------------------------------------------------

This program would produce:

Foundation Brick Properties

Length    = 4.24

Height    = 3.55

Thickness = 3.45

Cement Volume = 15.38



Press any key to continue...
 

Using the Default Constructor

  1. Access the Students.h file and change it as follows:
     
    //---------------------------------------------------------------------------
    
    #ifndef StudentsH
    
    #define StudentsH
    
    #include <string> 
    
    using namespace std;
    
    //---------------------------------------------------------------------------
    
    class TStudent
    
    {
    
    public:
    
         TStudent();
    
        void  InitialValues(string fn, string ln,
    
                                     int DOB, int MOB, int YOB);
    
        void  Display();
    
    private:
    
        string FirstName;
    
        string LastName;
    
        int DayOfBirth;
    
        int MonthOfBirth;
    
        int YearOfBirth;
    
    };
    
    //---------------------------------------------------------------------------
    
    #endif
  2. Change the Students.cpp file accordingly:
     
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    //---------------------------------------------------------------------------
    
     TStudent::STudent()
    
    {
    
    }
    
    //---------------------------------------------------------------------------
    
    void  TStudent::InitialValues(string fn, string ln,
    
                                     int DOB, int MOB, int YOB)
    
    {
    
        FirstName    = fn;
    
        LastName     = ln;
    
        DayOfBirth   = DOB;
    
        MonthOfBirth = MOB;
    
        YearOfBirth  = YOB;
    
    }
    
    //---------------------------------------------------------------------------
    
    void  TStudent::Display()
    
    {
    
        // Display the characteristics of the student
    
        cout << "Characteristics of this student";
    
        cout << "\nFull Name: " << FirstName << " " << LastName;
    
        cout << "\nDate of Birth: " << DayOfBirth
    
             << "/" << MonthOfBirth << "/" << YearOfBirth << "\n";
    
    }
    
    //---------------------------------------------------------------------------
  3. Press F9 to test the program.

The Constructor Initializer

A constructor does not exist simply for cosmetic reasons. It can be used to initialize the member variables of an object. Therefore, a constructor provides a valuable alternative to a method initializer, the type of method we saw earlier.

To use a constructor to initialize the member variables of an object, provide as arguments the necessary variables that you intend to initialize. You do not have to initialize all member variables in the constructor, only those that need to be initialized. In fact, you should initialize only those members that you think the other objects or functions would need to provide when calling this object; this means that your object may have member variables that, either the external objects or functions do not need to modify (or access) or the member variable will be initialized later when called from the needed object or function. To initialize the members of our Brick object, its method constructor would be declared as in the following file:

Listing - Brick Unit - Header File: Bricks.h

//---------------------------------------------------------------------------

#ifndef BricksH

#define BricksH



//---------------------------------------------------------------------------

struct TBrick

{

public:

     TBrick();    // Default Constructor

     TBrick(double l, double h, double t);

    double  CementVolume();

    void  ShowProperties();

private:

    double Length;

    double Height;

    double Thickness;

};

//---------------------------------------------------------------------------

#endif

Listing - Brick Unit - Source File: Bricks.cpp

//---------------------------------------------------------------------------

#include <iostream>

#include <iomanip>

using namespace std;



#include "Bricks.h"



//---------------------------------------------------------------------------





//---------------------------------------------------------------------------

 TBrick::TBrick()

{

    //TODO: Add your source code here

}

//---------------------------------------------------------------------------

 TBrick::TBrick(double l, double h, double t)

{

    Length = l;

    Height = h;

    Thickness = t;

}

//---------------------------------------------------------------------------

double  TBrick::CementVolume()

{

    double Enclosure = 0.50; // This includes both walls of the brick itself

    double HoleLength = Length - 0.75; // Including both holes

    double HoleThickness = Thickness - Enclosure;

    double HoleVolume = HoleLength * HoleThickness * Height;

    double TotalVolume = Length * Height * Thickness;

    double ValidVolume = TotalVolume - HoleVolume;



    return ValidVolume;

}

//---------------------------------------------------------------------------

void  TBrick::ShowProperties()

{

    cout << "Foundation Brick Properties";

    cout << setiosflags(ios::fixed) << setprecision(2);

    cout << "\nLength    = " << Length; cout

         << "\nHeight    = " << Height;

    cout << "\nThickness = " << Thickness;

    cout << "\nCement Volume = " << CementVolume() << "\n";

}

//---------------------------------------------------------------------------

Main File: Main.cpp

//---------------------------------------------------------------------------



#include <iostream>

using namespace std;

#include "Bricks.h"

//---------------------------------------------------------------------------



//---------------------------------------------------------------------------

int main()

{

    TBrick Solid(4.15, 3.35, 3.05);

    Solid.ShowProperties();



    

    

    return 0;

}

//---------------------------------------------------------------------------

This would produce the following result:

Foundation Brick Properties

Length    = 4.15

Height    = 3.35

Thickness = 3.05

Cement Volume = 13.36



Press any key to continue...

To safeguard and protect the member variables of an object, we have learned to use set and get methods. If you use set methods to protect the variables of an object, you can conveniently call these methods from the constructor to initialize those member variables. Therefore, a constructor can also be used to call methods that hold the initial values of member variables.

At this time, we have learned that a constructor is mainly used to set the initial values of necessary member variables. When using set methods, our Brick object would be changed as follows:

Brick Unit - Header File: Bricks.h

//---------------------------------------------------------------------------

#ifndef BricksH

#define BricksH



//---------------------------------------------------------------------------

struct TBrick

{

public:

     TBrick();    // Default Constructor

     TBrick(double l, double h, double t);

    void  setLength(double l);

    void  setHeight(double h);

    void  setThickness(double t);

    double  CementVolume();

    void  ShowProperties();

private:

    double Length;

    double Height;

    double Thickness;

};

//---------------------------------------------------------------------------

#endif

Brick Unit - Source File: Brick.cpp

//---------------------------------------------------------------------------

#include <iostream>

#include <iomanip>

using namespace std;



#include "Bricks.h"



//---------------------------------------------------------------------------





//---------------------------------------------------------------------------

 TBrick::TBrick()

{

    //TODO: Add your source code here

}

//---------------------------------------------------------------------------

 TBrick::TBrick(double l, double h, double t)

{

    setLength(l);

    setHeight(h);

    setThickness(t);

}

//---------------------------------------------------------------------------

void  TBrick::setLength(double l)

{

    Length = l;

}

//---------------------------------------------------------------------------

void  TBrick::setHeight(double h)

{

   Height = h;

}

//---------------------------------------------------------------------------

void  TBrick::setThickness(double t)

{

    Thickness = t;

}

//---------------------------------------------------------------------------

double  TBrick::CementVolume()

{

    double Enclosure = 0.50; // This includes both walls of the brick itself

    double HoleLength = Length - 0.75; // Including both holes

    double HoleThickness = Thickness - Enclosure;

    double HoleVolume = HoleLength * HoleThickness * Height;

    double TotalVolume = Length * Height * Thickness;

    double ValidVolume = TotalVolume - HoleVolume;



    return ValidVolume;

}

//---------------------------------------------------------------------------

void  TBrick::ShowProperties()

{

    cout << "Foundation Brick Properties";

    cout << setiosflags(ios::fixed) << setprecision(2);

    cout << "\nLength    = " << Length; cout

         << "\nHeight    = " << Height;

    cout << "\nThickness = " << Thickness;

    cout << "\nCement Volume = " << CementVolume() << "\n";

}

//---------------------------------------------------------------------------

Main File: Main.cpp

//---------------------------------------------------------------------------



#include <iostream>

using namespace std;

#include "Bricks.h"

//---------------------------------------------------------------------------



//---------------------------------------------------------------------------

int main()

{

    TBrick Solid(4.15, 3.35, 3.05);

    Solid.ShowProperties();



    

    

    return 0;

}

//---------------------------------------------------------------------------

This would produce:

Foundation Brick Properties

Length    = 4.15

Height    = 3.35

Thickness = 3.05

Cement Volume = 13.36



Press any key to continue...
 

Initializing With the Constructor

  1. Add a constructor to the Students object as follows:
     
    //---------------------------------------------------------------------------
    
    #ifndef StudentsH
    
    #define StudentsH
    
    #include <iostream>
    
    //---------------------------------------------------------------------------
    
    class TStudent
    
    {
    
    public:
    
         TStudent(string fn, string ln,
    
                            int DOB, int MOB, int YOB);
    
        void  Display();
    
    private:
    
        string FirstName;
    
        string LastName;
    
        int DayOfBirth;
    
        int MonthOfBirth;
    
        int YearOfBirth;
    
    };
    
    //---------------------------------------------------------------------------
    
    #endif
  2. Change the Students.cpp file: 
     
    //---------------------------------------------------------------------------
    
    
    
    using namespace std;
    
    
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    //---------------------------------------------------------------------------
    
     TStudent::TStudent(string fn, string ln,
    
                                  int DOB, int MOB, int YOB)
    
    {
    
        FirstName    = fn;
    
        LastName     = ln;
    
        DayOfBirth   = DOB;
    
        MonthOfBirth = MOB;
    
        YearOfBirth  = YOB;
    
    }
    
    //---------------------------------------------------------------------------
    
    void  TStudent::Display()
    
    {
    
        // Display the characteristics of the student
    
        cout << "Characteristics of this student";
    
        cout << "\nFull Name: " << FirstName << " " << LastName;
    
        cout << "\nDate of Birth: " << DayOfBirth
    
             << "/" << MonthOfBirth << "/" << YearOfBirth << "\n";
    
    }
    
    //---------------------------------------------------------------------------
  3. Finally, change the main():
     
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    void  Exit()
    
    {
    
        cout << "\n\nPress any key to continue...";
    
        
    
    }
    
    //---------------------------------------------------------------------------
    
    int main()
    
    {
    
        TStudent SecondGrade("Paul", "Waller", 12, 10, 1988);
    
        SecondGrade.Display();
    
    
    
        Exit();
    
        return 0;
    
    }
    
    //---------------------------------------------------------------------------
  4. Press F9 to test the program:

    Characteristics of this student Full Name: John Doe Date of Birth: 1/1/1990Press any key to continue...
  5. Return to your programming environment.

Constructor Overloading

Like an ordinary method, a construction can be overloaded. This means that you can have different constructors following the rules of overloading a function. Since we saw that a constructor can be used to initialize the member variables of its object, you can use multiple constructors to apply different initializations.

If you declare a constructor as

TBrick Foundation;

you can use it to call other method members of the same object. The problem is that if you just try to call a method that displays the values of the member variables, you will get bizarre and unpredictable results. Consider the TBrick object created as

//---------------------------------------------------------------------------

struct TBrick

{

public:

     TBrick();

    double  CementVolume();

    void  ShowProperties();

private:

    double Length;

    double Height;

    double Thickness;

};

//---------------------------------------------------------------------------

And implemented as

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;



#include "Bricks.h"

//---------------------------------------------------------------------------



 TBrick::TBrick()

{

    //TODO: Add your source code here

}

//---------------------------------------------------------------------------

double  TBrick::CementVolume()

{

    double Enclosure = 0.50; // This includes both walls of the brick itself

    double HoleLength = Length - 0.75; // Including both holes double

    double HoleThickness = Thickness - Enclosure;

    double HoleVolume = HoleLength * HoleThickness * Height;

    double TotalVolume = Length * Height * Thickness;

    double ValidVolume = TotalVolume - HoleVolume;



    return ValidVolume;

}

//---------------------------------------------------------------------------

void  TBrick::ShowProperties()

{

    cout << "Foundation Brick Properties";

    cout << "\nLength = " << Length;

    cout << "\nHeight = " << Height;

    cout << "\nThickness = " << Thickness;

    cout << "\nCement Volume = " << CementVolume() << "\n";

}

//---------------------------------------------------------------------------

If you declare the TBrick object using the default constructor, and decide to call a method that displays the variables values, you could write it like this:

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;

#include "Bricks.h"

//---------------------------------------------------------------------------





int main()

{

    TBrick Mango;



    Mango.ShowProperties();



    

    

    return 0;

}

//---------------------------------------------------------------------------

This would produce the following result:

Foundation Brick Properties

Length = nan

Height = 2.53988e-314

Thickness = 2.122e-314

Cement Volume = nan



Press any key to continue...

As you can see, these values do not make sense to us.

To make sure that a calling function does not have to supply values for the member variables, you can also use the empty constructor to supply default values to these variables. If you simply use the default constructor to get the values of the member variables, the object would use the values given in the empty constructor and perform all necessary operations:

 TBrick::TBrick()

{

    Length = 4.15;

    Height = 3.55;

    Thickness = 3.75;

}

This time, the same program would produce a sound result:

Foundation Brick Properties

Length = 4.15

Height = 3.55

Thickness = 3.75

Cement Volume = 16.0194



Press any key to continue...

This technique of using the default constructor allows you to conveniently supply default values for the member variables. As flexible as this is, you can use a certain constructor to initialize just one of the member variables and supply default values for the others. When constructing a brick, one of the dimensions would be of primary importance because it influences what the brick is used for. On this exercise, let's allow a calling function to supply the length of the brick while we control the other two dimensions. We can declare more than one constructor in the header file:

Brick Unit - Header File: Brick.h

//---------------------------------------------------------------------------

#ifndef BricksH

#define BricksH



//---------------------------------------------------------------------------

class TBrick

{

public:

     TBrick();

     TBrick(double L);

    double  CementVolume();

    void  ShowProperties();

private:

    double Length;

    double Height;

    double Thickness;

};

//---------------------------------------------------------------------------

#endif

Brick Unit - Source File: Brick.cpp

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;



#include "Bricks.h"

//---------------------------------------------------------------------------



 TBrick::TBrick()

{

    Length = 4.15;

    Height = 3.55;

    Thickness = 3.75;

}

//---------------------------------------------------------------------------

 TBrick::TBrick(double L)

{

    Length = L;

    Height = 5.25;

    Thickness = 4.55;

}

//---------------------------------------------------------------------------

double  TBrick::CementVolume()

{

    ...

}

//---------------------------------------------------------------------------

void  TBrick::ShowProperties()

{

    ...

}

//---------------------------------------------------------------------------

Since this constructor takes one argument, when declaring an object that would use this constructor, assign only one value to the argument variable. Such a value is provided in the parentheses allocated to the instance of the object. Here is an example:

Main File: Main.cpp

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;

#include "Bricks.h"

//---------------------------------------------------------------------------





int main()

{

    // Brick with default dimensions

    TBrick Mather;

    Mather.ShowProperties();

    cout << endl;



    // Brick with a supplied length

    TBrick BedTimer(5.55);

    BedTimer.ShowProperties();



    

    

    return 0;

}

//---------------------------------------------------------------------------

This would produce the following result:

Foundation Brick Properties

Length = 4.15

Height = 3.55

Thickness = 3.75

Cement Volume = 16.0194



Foundation Brick Properties

Length = 5.55

Height = 5.25

Thickness = 4.55

Cement Volume = 30.5156



Press any key to continue...

If you declare different constructors with different arguments to initialize (remember the rules of function overloading), when declaring these objects, make sure you initialize each instance with the right number of arguments; otherwise, the compiler would complain.

Here is our program that makes use of three constructors, each with different arguments:

Brick Unit - Header File: Brick.h

//---------------------------------------------------------------------------

#ifndef BricksH

#define BricksH



//---------------------------------------------------------------------------

class TBrick

{

public:

     TBrick();

     TBrick(double L);

     TBrick(double L, double h, double t);

    double  CementVolume();

    void  ShowProperties();

private:

    double Length;

    double Height;

    double Thickness;

};

//---------------------------------------------------------------------------

#endif

The new constructor can be implemented as follows:

//---------------------------------------------------------------------------

 TBrick::TBrick(double L, double h, double t)

{

    Length = L;

    Height = h;

    Thickness = t;

}//---------------------------------------------------------------------------

Main File: Main.cpp

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;

#include "Bricks.h"

//---------------------------------------------------------------------------





int main()

{

    // Brick with default dimensions

    TBrick GrayMatte;

    GrayMatte.ShowProperties();

    cout << endl;



    // Brick with a supplied length

    TBrick OldTimer(5.55);

    OldTimer.ShowProperties();

    cout << endl;



    // A Brick with set dimensions

    TBrick Fantasma(3.25, 3.05, 3.25);

    Fantasma.ShowProperties();



    

    

    return 0;

}

//---------------------------------------------------------------------------

This would produce:

Foundation Brick Properties

Length = 4.15

Height = 3.55

Thickness = 3.75

Cement Volume = 16.0194



Foundation Brick Properties

Length = 5.55

Height = 5.25

Thickness = 4.55

Cement Volume = 30.5156



Foundation Brick Properties

Length = 3.25

Height = 3.05

Thickness = 3.25

Cement Volume = 11.2469



Press any key to continue...

If you create an object and create it with only one constructor, if you create this constructor with at least one argument, the default constructor would not be available anymore. For example if you create a TBrick object as follows:

//---------------------------------------------------------------------------

#ifndef BricksH

#define BricksH



//---------------------------------------------------------------------------

class TBrick

{

public:

     TBrick(double L, double h, double t);

    double  CementVolume();

    void  ShowProperties();

private:

    double Length;

    double Height;

    double Thickness;

};

//---------------------------------------------------------------------------

#endif

and implement the TBrick(double L, double h, double t) constructor as we saw above, the following main() function would halt the program:

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;

#include "Bricks.h"

//---------------------------------------------------------------------------





int main()

{

    // The following (default) constructor is not available

    TBrick GrayMatte;

    GrayMatte.ShowProperties();

    cout << endl;



    // A Brick with set dimensions

    TBrick Fantasma(3.25, 3.05, 3.25);

    Fantasma.ShowProperties();



    

    

    return 0;

}

//---------------------------------------------------------------------------

Therefore, if you want to access a default constructor of an object, you have two alternatives:

  • If you don't create any constructor at all on an object, the default constructor would always be available whenever you invoke that object.
  • If you create at least one constructor on an object and supply at least one argument to that constructor, you must explicitly create a default constructor for your object.

Based on what we have learned already, here is our complete program with set and get methods. 

Brick Unit - Header File: Brick.h

//---------------------------------------------------------------------------

#ifndef BricksH

#define BricksH



//---------------------------------------------------------------------------

class TBrick

{

public:

     TBrick();

     TBrick(double L);

     TBrick(double L, double h, double t);

    double  getLength() const;

    void  setLength(const double l);

    double  getHeight() const;

    void  setHeight(const double h);

    double  getThickness() const;

    void  setThickness(const double t);

    double  CementVolume();

    void  ShowProperties();

private:

    double Length;

    double Height;

    double Thickness;

};

//---------------------------------------------------------------------------

#endif

Brick Unit - Source File: Brick.cpp

//---------------------------------------------------------------------------

#include <iostream>

#include <iomanip>

using namespace std;



#include "Bricks.h"

//---------------------------------------------------------------------------



 TBrick::TBrick()

{

    Length = 4.15;

    Height = 3.55;

    Thickness = 3.75;

}

//---------------------------------------------------------------------------

 TBrick::TBrick(double L)

{

    Length = L;

    Height = 5.25;

    Thickness = 4.55;

}

//---------------------------------------------------------------------------

 TBrick::TBrick(double L, double h, double t)

{

    Length = L;

    Height = h;

    Thickness = t;

}

//---------------------------------------------------------------------------

double  TBrick::getLength() const

{

    return Length;

}

//---------------------------------------------------------------------------

void  TBrick::setLength(const double l)

{

    Length = l;

}

//---------------------------------------------------------------------------

double  TBrick::getHeight() const

{

    return Height;

}

//---------------------------------------------------------------------------

void  TBrick::setHeight(const double h)

{

    Height = h;

}

//---------------------------------------------------------------------------

double  TBrick::getThickness() const

{

    return Thickness;

}

//---------------------------------------------------------------------------

void  TBrick::setThickness(const double t)

{

    Thickness = t;

}

//---------------------------------------------------------------------------

double  TBrick::CementVolume()

{

    double Enclosure = 0.50; // This includes both walls of the brick itself

    double HoleLength = Length - 0.75; // Including both holes double

    double HoleThickness = Thickness - Enclosure;

    double HoleVolume = HoleLength * HoleThickness * Height;

    double TotalVolume = Length * Height * Thickness;

    double ValidVolume = TotalVolume - HoleVolume;



    return ValidVolume;

}

//---------------------------------------------------------------------------

void  TBrick::ShowProperties()

{

    cout << "Foundation Brick Properties";

    cout << setiosflags(ios::fixed) << setprecision(2);

    cout << "\nLength = " << Length;

    cout << "\nHeight = " << Height;

    cout << "\nThickness = " << Thickness;

    cout << "\nCement Volume = " << CementVolume() << "\n";

}

//---------------------------------------------------------------------------

Main File: Main.cpp

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;

#include "Bricks.h"

//---------------------------------------------------------------------------





int main()

{

    // Brick with default dimensions

    TBrick GrayMatte;

    GrayMatte.ShowProperties();

    cout << endl;



    // Brick with a supplied length

    TBrick OldTimer(5.55);

    OldTimer.ShowProperties();

    cout << endl;



    // A Brick with user supplied dimensions

    double len, hgt, thk;

    cout << "\nEnter the dimensions of the brick\n";

    cout << "Length: ";

    cin >> len;

    cout << "Height: ";

    cin >> hgt;

    cout << "Thickness: ";

    cin >> thk;

    cout << endl;

    TBrick Fantasma(len, hgt, thk);

    Fantasma.ShowProperties();



    

    

    

    return 0;

}

//---------------------------------------------------------------------------

Here is an example of running the program: 

Foundation Brick Properties

Length = 4.15

Height = 3.55

Thickness = 3.75

Cement Volume = 16.02



Foundation Brick Properties

Length = 5.55

Height = 5.25

Thickness = 4.55

Cement Volume = 30.52





Enter the dimensions of the brick

Length: 6.25

Height: 5.85

Thickness: 4.55



Foundation Brick Properties

Length = 6.25

Height = 5.85

Thickness = 4.55

Cement Volume = 36.05



Press any key to continue...
 

Overloading the Constructor

  1. To use an empty constructor that initializes the member variables, change the Students.h file as follows:
     
    //---------------------------------------------------------------------------
    
    #ifndef StudentsH
    
    #define StudentsH
    
    #include <iostream>
    
    //---------------------------------------------------------------------------
    
    class TStudent
    
    {
    
    public:
    
         TStudent();
    
         TStudent(string fn, string ln,
    
                            int DOB, int MOB, int YOB);
    
        void  Display();
    
    private:
    
        string FirstName;
    
        string LastName;
    
        int DayOfBirth;
    
        int MonthOfBirth;
    
        int YearOfBirth;
    
    };
    
    //---------------------------------------------------------------------------
    
    #endif
  2. Implement the new constructor in the Student.cpp file as follows:

    //---------------------------------------------------------------------------
    
    _fastcall TStudent::TStudent()
    
    {
    
        FirstName    = "Paul";
    
        LastName     = "Kamus";
    
        DayOfBirth   = 28;
    
        MonthOfBirth = 5;
    
        YearOfBirth  = 1986;
    
    }
    
    //---------------------------------------------------------------------------
  3. To test both constructors, change the main() function as follows:

    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    void  Exit()
    
    {
    
        cout << "\n\nPress any key to continue...";
    
        
    
    }
    
    //---------------------------------------------------------------------------
    
    int main()
    
    {
    
        TStudent SampleStudent;
    
        SampleStudent.Display();
    
        cout << endl;
    
    
    
        TStudent Complete("Alexander", "Biyidi", 30, 4, 1988);
    
        Complete.Display();
    
    
    
        Exit();
    
        return 0;
    
    }
    
    //---------------------------------------------------------------------------
  4. To test the program, press F9:
     
    Characteristics of this student
    
    Full Name: Paul Kamus
    
    Date of Birth: 28/5/1986
    
    
    
    Characteristics of this student
    
    Full Name: Alexander Biyidi
    
    Date of Birth: 30/4/1988
    
    
    
    
    
    Press any key to continue...

  5. Return to your programming environment.
  6. Now, we will use two more constructors. One of the constructors will initialize only the name of the student. Another constructor will set default values for the date of birth. Both constructors use the same technique but accomplish different purposes. Therefore, change the TStudent class as follows:
     
    //---------------------------------------------------------------------------
    
    #ifndef StudentsH
    
    #define StudentsH
    
    #include <iostream>
    
    //---------------------------------------------------------------------------
    
    class TStudent
    
    {
    
    public:
    
         TStudent();  // Default Constructor
    
         TStudent(string F, string L); // Name Initializer
    
         TStudent(int DOB, int MOB, int YOB); // Initial Date of birth
    
         TStudent(string fn, string ln,
    
                            int DOB, int MOB, int YOB); // Complete Constructor
    
        void  Display();
    
    private:
    
        string FirstName;
    
        string LastName;
    
        int DayOfBirth;
    
        int MonthOfBirth;
    
        int YearOfBirth;
    
    };
    
    //---------------------------------------------------------------------------
    
    #endif
  7. Implement the constructors in the Students.cpp file as follows:

    //---------------------------------------------------------------------------
    
    
    
    using namespace std;
    
    
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    //---------------------------------------------------------------------------
    
    _fastcall TStudent::TStudent()
    
    {
    
        FirstName    = "John";
    
        LastName     = "Doe";
    
        DayOfBirth   = 1;
    
        MonthOfBirth = 1;
    
        YearOfBirth  = 1990;
    
    }
    
    //---------------------------------------------------------------------------
    
     TStudent::TStudent(string FN, string LN)
    
    {
    
        FirstName    = FN;
    
        LastName     = LN;
    
        DayOfBirth   = 1;
    
        MonthOfBirth = 1;
    
        YearOfBirth  = 1985;
    
    }
    
    //---------------------------------------------------------------------------
    
     TStudent::TStudent(int DOB, int MOB, int YOB)
    
    {                  
    
        FirstName    = "William";
    
        LastName     = "Smith";
    
        DayOfBirth   = DOB;
    
        MonthOfBirth = MOB;
    
        YearOfBirth  = YOB;
    
    }
    
    //---------------------------------------------------------------------------
    
     TStudent::TStudent(string fn, string ln,
    
                                  int DOB, int MOB, int YOB)
    
    {
    
        FirstName    = fn;
    
        LastName     = ln;
    
        DayOfBirth   = DOB;
    
        MonthOfBirth = MOB;
    
        YearOfBirth  = YOB;
    
    }
    
    //---------------------------------------------------------------------------
    
    void  TStudent::Display()
    
    {
    
        // Display the characteristics of the student
    
        cout << "Characteristics of this student";
    
        cout << "\nFull Name: " << FirstName << " " << LastName;
    
        cout << "\nDate of Birth: " << DayOfBirth
    
             << "/" << MonthOfBirth << "/" << YearOfBirth << "\n";
    
    }
    
    //---------------------------------------------------------------------------
  8. Test the constructors in the main() function with the following:

    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    void  Exit()
    
    {
    
        cout << "\n\nPress any key to continue...";
    
        
    
    }
    
    //---------------------------------------------------------------------------
    
    int main()
    
    {
    
        TStudent DefaultStudent;
    
        DefaultStudent.Display();
    
        cout << endl;
    
    
    
        TStudent WithNameOnly("Genevieve", "Souchon");
    
        WithNameOnly.Display();
    
        cout << endl;
    
    
    
        TStudent ByDateOfBirth(12, 5, 1987);
    
        ByDateOfBirth.Display();
    
        cout << endl;
    
    
    
        TStudent Typical("William", "Tobolowski", 5, 15, 1985);
    
        Typical.Display();
    
    
    
        Exit();
    
        return 0;
    
    }
    
    //---------------------------------------------------------------------------
  9. Press F9 to test the program:
     
    Characteristics of this student
    
    Full Name: John Doe
    
    Date of Birth: 1/1/1990
    
    
    
    Characteristics of this student
    
    Full Name: Genevieve Souchon
    
    Date of Birth: 1/1/1985
    
    
    
    Characteristics of this student
    
    Full Name: William Smith
    
    Date of Birth: 12/5/1987
    
    
    
    Characteristics of this student
    
    Full Name: William Tobolowski
    
    Date of Birth: 5/15/1985
    
    
    
    
    
    Press any key to continue...

  10. Return to your programming environment

 

Techniques of Initializing With a Constructor

We have already seen various techniques of initializing member variables and implementing member methods. In the same way, a constructor can be defined locally, in the header file:

Brick Unit - Header File: Brick.h

//---------------------------------------------------------------------------

#ifndef BricksH

#define BricksH



//---------------------------------------------------------------------------

class TBrick

{

public:

     TBrick(double L, double h, double t) { Length = L; Height = h; Thickness = t; }

    double  getLength() const;

    void  setLength(const double l);

    double  getHeight() const;

    void  setHeight(const double h);

    double  getThickness() const;

    void  setThickness(const double t);

    double  CementVolume();

    void  ShowProperties();

private:

    double Length;

    double Height;

    double Thickness;

};

//---------------------------------------------------------------------------

#endif

There is another technique you can use to initialize the member variables in a constructor. To initialize the list of members, after defining the constructor, which is after the parentheses, type a colon, followed by the name of an argument and include the initial value in parentheses. The initializations are separated by a comma. Since the constructor is a method, make sure you provide its body.

To initialize the members of our TBrick object, we can type:

Brick Unit - Header File: Brick.h

//---------------------------------------------------------------------------

#ifndef BricksH

#define BricksH



//---------------------------------------------------------------------------

class TBrick

{

public:

     TBrick() : Length(3.25), Height(2.55), Thickness(3.55) {}

     TBrick(double L, double h, double t) { Length = L; Height = h; Thickness = t; }

    double  getLength() const;

    void  setLength(const double l);

    double  getHeight() const;

    void  setHeight(const double h);

    double  getThickness() const;

    void  setThickness(const double t);

    double  CementVolume();

    void  ShowProperties();

private:

    double Length;

    double Height;

    double Thickness;

};

//---------------------------------------------------------------------------

#endif

The source file would be as follows. 

Brick Unit - Source File: Brick.cpp

//---------------------------------------------------------------------------

#include <iostream>

#include <iomanip>

using namespace std;



#include "Bricks.h"

//---------------------------------------------------------------------------



//---------------------------------------------------------------------------

double  TBrick::getLength() const

{

    return Length;

}

//---------------------------------------------------------------------------

void  TBrick::setLength(const double l)

{

    Length = l;

}

//---------------------------------------------------------------------------

double  TBrick::getHeight() const

{

    return Height;

}

//---------------------------------------------------------------------------

void  TBrick::setHeight(const double h)

{

    Height = h;

}

//---------------------------------------------------------------------------

double  TBrick::getThickness() const

{

    return Thickness;

}

//---------------------------------------------------------------------------

void  TBrick::setThickness(const double t)

{

    Thickness = t;

}

//---------------------------------------------------------------------------

double  TBrick::CementVolume()

{

    double Enclosure = 0.50; // This includes both walls of the brick itself

    double HoleLength = Length - 0.75; // Including both holes double

    double HoleThickness = Thickness - Enclosure;

    double HoleVolume = HoleLength * HoleThickness * Height;

    double TotalVolume = Length * Height * Thickness;

    double ValidVolume = TotalVolume - HoleVolume;



    return ValidVolume;

}

//---------------------------------------------------------------------------

void  TBrick::ShowProperties()

{

    cout << "Foundation Brick Properties";

    cout << setiosflags(ios::fixed) << setprecision(2);

    cout << "\nLength = " << Length;

    cout << "\nHeight = " << Height;

    cout << "\nThickness = " << Thickness;

    cout << "\nCement Volume = " << CementVolume() << "\n";

}

//---------------------------------------------------------------------------

To test the program, we would implement the main() function as follows. 

Main Unit - Source File: Main.cpp

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;

#include "Bricks.h"

//---------------------------------------------------------------------------





int main()

{

    TBrick Lott;

    Lott.ShowProperties();



    

    

    return 0;

}

//---------------------------------------------------------------------------

We can use the same technique to initialize other constructors if more than one. We can therefore change the constructors of the program we had earlier using this syntax. 

Brick Unit - Header File: Brick.h

//---------------------------------------------------------------------------

#ifndef BricksH

#define BricksH



//---------------------------------------------------------------------------

class TBrick

{

public:

     TBrick() : Length(0), Height(0), Thickness(0) {}

     TBrick(double L) : Length(L), Height(4.35), Thickness(3.05) {}

     TBrick(double L, double h, double t) : Length(L), Height(h), Thickness(t) {}

    double  getLength() const;

    void  setLength(const double l);

    double  getHeight() const;

    void  setHeight(const double h);

    double  getThickness() const;

    void  setThickness(const double t);

    double  CementVolume();

    void  ShowProperties();

private:

    double Length;

    double Height;

    double Thickness;

};

//---------------------------------------------------------------------------

#endif

The source file remains the same as above. The main() function would be implemented as follows. 

Main.cpp

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;

#include "Bricks.h"

//---------------------------------------------------------------------------





int main()

{

    // Calling the object using the default constructor

    TBrick Lott;

    Lott.ShowProperties();



    // This time, the program will use the constructor that has one argument

    TBrick Motto(6.12);

    Motto.ShowProperties();



    // The following object is supplied with arguments

    TBrick Hott(5.25, 3.55, 3.55);

    Hott.ShowProperties();



    

    

    return 0;

}

//---------------------------------------------------------------------------

This would produce the following result:

Foundation Brick Properties

Length = 0.00

Height = 0.00

Thickness = 0.00

Cement Volume = 0.00

Foundation Brick Properties

Length = 6.12

Height = 4.35

Thickness = 3.05

Cement Volume = 21.63

Foundation Brick Properties

Length = 5.25

Height = 3.55

Thickness = 3.55

Cement Volume = 17.44



Press any key to continue...

If you do not want to implement these constructors in the header file, you can carry them to the source file, using the same syntax, like this:

Brick Unit - Header File: Brick.h

//---------------------------------------------------------------------------

#ifndef BricksH

#define BricksH



//---------------------------------------------------------------------------

class TBrick

{

public:

     TBrick();

     TBrick(double L);

     TBrick(double L, double h, double t);

    double  getLength() const;

    void  setLength(const double l);

    double  getHeight() const;

    void  setHeight(const double h);

    double  getThickness() const;

    void  setThickness(const double t);

    double  CementVolume();

    void  ShowProperties();

private:

    double Length;

    double Height;

    double Thickness;

};

//---------------------------------------------------------------------------

#endif

Brick Unit - Source File: Brick.cpp

//---------------------------------------------------------------------------

#include <iostream>

#include <iomanip>

using namespace std;



#include "Bricks.h"

//---------------------------------------------------------------------------



 TBrick::TBrick() : Length(0), Height(0), Thickness(0)

{

}

//---------------------------------------------------------------------------

 TBrick::TBrick(double L) : Length(L), Height(4.35), Thickness(3.05)

{

}

//---------------------------------------------------------------------------

 TBrick::TBrick(double L, double h, double t)

    : Length(L), Height(h), Thickness(t)

{

}

//---------------------------------------------------------------------------

. . .
 

Initializing With Constructors

  1. To implement the both default and the complete constructors in the source file, change the listing of Students.h as follows:
     
    //---------------------------------------------------------------------------
    
    #ifndef StudentsH
    
    #define StudentsH
    
    #include <string>
    
    using namespace std;
    
    //---------------------------------------------------------------------------
    
    class TStudent
    
    {
    
    public:
    
         TStudent() { FirstName = "John"; LastName = "Doe";
    
                                DayOfBirth = 1; MonthOfBirth = 1;
    
                                YearOfBirth = 1990;
    
                              }
    
         TStudent(string F, string L);        // Name Initializer
    
         TStudent(int DOB, int MOB, int YOB); // Initial Date of birth
    
         TStudent(string fn, string ln,
    
                            int DOB, int MOB, int YOB)
    
                            {   FirstName    = fn;
    
                                LastName     = ln;
    
                                DayOfBirth   = DOB;
    
                                MonthOfBirth = MOB;
    
                                YearOfBirth  = YOB;
    
                            }
    
        void  Display();
    
    private:
    
        string FirstName;
    
        string LastName;
    
        int DayOfBirth;
    
        int MonthOfBirth;
    
        int YearOfBirth;
    
    };
    
    //---------------------------------------------------------------------------
    
    #endif
  2. Make sure you change the implementation file as follows:

  3. To use the new technique of initializing the member variables, implement the constructors in the Students.cpp file as follows:

    //---------------------------------------------------------------------------
    
    
    
    using namespace std;
    
    
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    //---------------------------------------------------------------------------
    
     TStudent::TStudent(string FN, string LN)
    
    {
    
        FirstName    = FN;
    
        LastName     = LN;
    
        DayOfBirth   = 1;
    
        MonthOfBirth = 1;
    
        YearOfBirth  = 1985;
    
    }
    
    //---------------------------------------------------------------------------
    
     TStudent::TStudent(int DOB, int MOB, int YOB)
    
    {                  
    
        FirstName    = "William";
    
        LastName     = "Smith";
    
        DayOfBirth   = DOB;
    
        MonthOfBirth = MOB;
    
        YearOfBirth  = YOB;
    
    }
    
    //---------------------------------------------------------------------------
    
    void  TStudent::Display()
    
    {
    
        // Display the characteristics of the student
    
        cout << "Characteristics of this student";
    
        cout << "\nFull Name: " << FirstName << " " << LastName;
    
        cout << "\nDate of Birth: " << DayOfBirth
    
             << "/" << MonthOfBirth << "/" << YearOfBirth << "\n";
    
    }
    
    //---------------------------------------------------------------------------
  4. Test the program and return to your programming environment.
  5. To initialize the member variables using parentheses, change the Students.h file as follows:
     
    //---------------------------------------------------------------------------
    
    #ifndef StudentsH
    
    #define StudentsH
    
    #include <iostream>
    
    //---------------------------------------------------------------------------
    
    class TStudent
    
    {
    
    public:
    
         TStudent() : FirstName("John"),
    
                                LastName("Doe"),
    
                                DayOfBirth(1),
    
                                MonthOfBirth(1),
    
                                YearOfBirth(1990)
    
                              {}
    
         TStudent(string F, string L);        // Name Initializer
    
         TStudent(int DOB, int MOB, int YOB); // Initial Date of birth
    
         TStudent(string fn, string ln,
    
                            int DOB, int MOB, int YOB)
    
                            :   FirstName(fn),
    
                                LastName(ln),
    
                                DayOfBirth(DOB),
    
                                MonthOfBirth(MOB),
    
                                YearOfBirth(YOB)
    
                            {}
    
        void  Display();
    
    private:
    
        string FirstName;
    
        string LastName;
    
        int DayOfBirth;
    
        int MonthOfBirth;
    
        int YearOfBirth;
    
    };
    
    //---------------------------------------------------------------------------
    
    #endif
  6. Test the program and return to your programming environment
  7. To use this initialization in the implementation file, change the Students.h file as follows:
     
    //---------------------------------------------------------------------------
    
    #ifndef StudentsH
    
    #define StudentsH
    
    #include <string>
    
    using namespace std;
    
    //---------------------------------------------------------------------------
    
    class TStudent
    
    {
    
    public:
    
         TStudent();
    
         TStudent(string F, string L);        // Name Initializer
    
         TStudent(int DOB, int MOB, int YOB); // Initial Date of birth
    
         TStudent(string fn, string ln,
    
                            int DOB, int MOB, int YOB);
    
        void  Display();
    
    private:
    
        string FirstName;
    
        string LastName;
    
        int DayOfBirth;
    
        int MonthOfBirth;
    
        int YearOfBirth;
    
    };
    
    //---------------------------------------------------------------------------
    
    #endif
  8. Change the Students.cpp file as follows:
     
    //---------------------------------------------------------------------------
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    
    
    //---------------------------------------------------------------------------
    
     TStudent::TStudent() : FirstName("John"), LastName("Doe"),
    
                                      DayOfBirth(1), MonthOfBirth(1),
    
                                      YearOfBirth(1990)
    
    {
    
    }
    
    //---------------------------------------------------------------------------
    
     TStudent::TStudent(string FN, string LN)
    
        : FirstName(FN), LastName(LN),
    
          DayOfBirth(1), MonthOfBirth(1), YearOfBirth(1985)
    
    {
    
        
    
    }
    
    //---------------------------------------------------------------------------
    
     TStudent::TStudent(int DOB, int MOB, int YOB)
    
        : FirstName("William"), LastName("Smith"),
    
          DayOfBirth(DOB), MonthOfBirth(MOB), YearOfBirth(YOB)
    
    {
    
    }
    
    //---------------------------------------------------------------------------
    
     TStudent::TStudent(string fn, string ln,
    
                                  int DOB, int MOB, int YOB)
    
        : FirstName(fn),
    
          LastName(ln),
    
          DayOfBirth(DOB),
    
          MonthOfBirth(MOB),
    
          YearOfBirth(YOB)
    
    {
    
    }
    
    //---------------------------------------------------------------------------
    
    void  TStudent::Display()
    
    {
    
        // Display the characteristics of the student
    
        cout << "Characteristics of this student";
    
        cout << "\nFull Name: " << FirstName << " " << LastName;
    
        cout << "\nDate of Birth: " << DayOfBirth
    
             << "/" << MonthOfBirth << "/" << YearOfBirth << "\n";
    
    }
    
    //---------------------------------------------------------------------------
  9. Press F9 to test the program and return to your programming environment.

The Copy Constructor

 

Copying an Object

After creating an object and assigning appropriate values to its members, you can perform any regular operation on it. Although this gets a little particular with objects, which will be expanded when learning about operator overloading, you can assign an object to another object. We have already learned:

How to assign Example
A value to a variable int a = 250;
The value of one variable to another NbrOfBoys = NbrOfGirls;
A value to an object’s member Video.Category = “Drama”

Assigning a variable to another is equivalent to making a copy of that variable. As you assign a variable to another, you can assign one object to another. Both objects must be recognizably equivalent to the compiler. Imagine you want to build the same brick twice. All you have to do is to assign one brick to another, which is take care of in the following main() function:

//---------------------------------------------------------------------------

#include <iostream>

using namespace std;

#include "Bricks.h"

//---------------------------------------------------------------------------





int main()

{

    // Declaring one brick

    TBrick Hott(5.25, 3.55, 3.55);

    Hott.ShowProperties();

    cout << endl;



    // Assigning one brick to another

    TBrick Bosco = Hott;

    Bosco.ShowProperties();



    

    

    return 0;

}

//---------------------------------------------------------------------------

Here is an example of running the program:

Foundation Brick Properties

Length = 5.25

Height = 3.55

Thickness = 3.55

Cement Volume = 17.44



Foundation Brick Properties

Length = 5.25

Height = 3.55

Thickness = 3.55

Cement Volume = 17.44



Press any key to continue...

Notice that both orders display the same thing.

Using a Copy Constructor

Besides the default constructor, the compiler creates another function method called the copy constructor. This is another special method that is used for operations such as copying an object into another.

Remember, we have seen that a variable can be initialized using the = symbol or the parentheses, as in the following example:

//---------------------------------------------------------------------------

#include <iostream>

#include <iomanip>

using namespace std;

//---------------------------------------------------------------------------



int main()

{

    // Assigning a value to a variable using the = sign

    int CheeseSteak = 2;

    // Assigning a value using the parenthesis

    int TunaSalad(4);

    // Assigning one variable to another

    int TurkeyHam(TunaSalad);

    // Assignment with parenthesis

    double PriceCS(3.12); 

    double PriceTS = 2.95;

    // Assigning the price of one item to another

    double PriceTH(PriceTS);

    

    double TotalCS, TotalTS, TotalTH;

    TotalCS = CheeseSteak * PriceCS;

    TotalTS = TunaSalad * PriceTS;

    TotalTH = TurkeyHam * PriceTH;



    cout << "Total Order\n";

    cout << setiosflags(ios::fixed) << setprecision(2);

    cout << CheeseSteak << " orders of Cheese Steak, Price = $"

         << TotalCS << "\n";

    cout << TunaSalad << " orders of Tuna Salad, Price = $"

         << TotalTS << endl;

    cout << TurkeyHam << " orders of Turkey Ham, Price = $" << TotalTH << endl;



    

    

    return 0;

}

//---------------------------------------------------------------------------

This would produce:

Total Order

2 orders of Cheese Steak, Price = $6.24

4 orders of Tuna Salad, Price = $11.80

4 orders of Turkey Ham, Price = $11.80



Press any key to continue...

When you have two instances of an object such as:

Video Drama, Comedy;

you can assign one object to another like this:

Drama = Comedy;

This operation indeed assigns a copy of the Comedy Video to the Drama object. Behind the scenes, this transaction is handled by the copy constructor. Like the default constructor, the compiler automatically creates a copy constructor when an onbject is instantiated. Like the default constructor, you can explicitly create a copy constructor; it has a different syntax although it also holds the same name as the object. The syntax of the copy constructor.

ObjectName(ObjectName& Name);

The copy constructor takes one argument, which is the same as the object itself. When a copy is made, it holds and carries the building constructor of the object. This object is specified as the argument. As a copy whose value still resides with the object, this argument should be passed as a reference. As a copy, this argument should not be modified. It is only used to pass a copy of the object to the other objects that need it. Therefore, the argument should not be modified. As a result, it should be declared as a constant. The syntax of the copy constructor becomes:

ObjectName(const ObjectName& Name);

To copy one object to another, first create a copy constructor:

//---------------------------------------------------------------------------

#ifndef BricksH

#define BricksH

//---------------------------------------------------------------------------

class TBrick

{

public:

     TBrick();

     TBrick(double L, double h, double t);

     TBrick(const TBrick &Brk);

    double  getLength() const;

    void  setLength(const double l);

    double  getHeight() const;

    void  setHeight(const double h);

    double  getThickness() const;

    void  setThickness(const double t);

    double  CementVolume();

    void  ShowProperties();

private:

    double Length;

    double Height;

    double Thickness;

};

//---------------------------------------------------------------------------

#endif

In the implementation, assign a member variable of the copy constructor to the equivalent member of the object:

//---------------------------------------------------------------------------

 TBrick::TBrick(const TBrick& B)

{

    Length    = B.Length;

    Height    = B.Height;

    Thickness = B.Thickness;

}

//---------------------------------------------------------------------------

Here is an example that uses a copy constructor to copy one order into another:

//---------------------------------------------------------------------------

#include <iostream>

#include <iomanip>

using namespace std;

#include "Bricks.h"

//---------------------------------------------------------------------------



int main()

{

    TBrick  Beam(7.25, 4.85, 5.15), Hoyt;

    Beam.ShowProperties();

    cout << endl;



    // Create the other brick similar to the first

    // Assigning using the assignment operator

    Hoyt = Beam;

    Hoyt.ShowProperties();

    cout << endl;



    // Assigning using the parentheses

    TBrick Mollo(Beam);

    Hoyt.ShowProperties();



    

    

    return 0;

}

//---------------------------------------------------------------------------

This would produce:

Foundation Brick Properties

Length = 7.25

Height = 4.85

Thickness = 5.15

Cement Volume = 34.50



Foundation Brick Properties

Length = 7.25

Height = 4.85

Thickness = 5.15

Cement Volume = 34.50



Foundation Brick Properties

Length = 7.25

Height = 4.85

Thickness = 5.15

Cement Volume = 34.50



Press any key to continue...
 

Using the Copy Constructor

  1. To use the default copy constructor created by the compiler, change the content of the main() function as follows:
     
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    #include "Students.h"
    
    //---------------------------------------------------------------------------
    
    int main()
    
    {
    
        TStudent Student1("Pamela", "Wattson", 2, 18, 1988);
    
        Student1.Display();
    
        cout << endl;
    
    
    
        TStudent DefaultStudent;
    
        DefaultStudent.Display();
    
        cout << endl;
    
    
    
        TStudent DuplicateHer = Student1;
    
        DuplicateHer.Display();
    
    
    
        return 0;
    
    }
    
    //---------------------------------------------------------------------------
  2. Execute the program to test it and return to your programming environment.
  3. To explicitly create your own copy constructor, declare one in the header file as follows:
    //---------------------------------------------------------------------------
    
    #ifndef StudentsH
    
    #define StudentsH
    
    #include <iostream>
    
    using namespace std;
    
    //---------------------------------------------------------------------------
    
    class TStudent
    
    {
    
    public:
    
         TStudent();
    
         TStudent(string F, string L);        // Name Initializer
    
         TStudent(int DOB, int MOB, int YOB); // Initial Date of birth
    
         TStudent(string fn, string ln,
    
                            int DOB, int MOB, int YOB);
    
         TStudent(const TStudent& S);
    
        void  Display();
    
    private:
    
        string FirstName;
    
        string LastName;
    
        int DayOfBirth;
    
        int MonthOfBirth;
    
        int YearOfBirth;
    
    };
    
    //---------------------------------------------------------------------------
    
    #endif
  4. Implement your copy constructor as follows:
     
    //---------------------------------------------------------------------------
    
     TStudent::TStudent(const TStudent& Stud)
    
        : FirstName(Stud.FirstName), LastName(Stud.LastName),
    
          DayOfBirth(Stud.DayOfBirth), MonthOfBirth(Stud.MonthOfBirth),
    
          YearOfBirth(Stud.YearOfBirth)
    
    {
    
    }
    
    //---------------------------------------------------------------------------
  5. Test the program again and return to your programming environment.
  6. Save the project.

Destructors

 

Introduction 

As opposed to a constructor, a destructor is called when a program has finished using an instance of an object. A destructor does the cleaning behind the scenes. Like the default constructor, the compiler always create a default destructor if you don't create one. Like the default constructor, a destructor also has the same name as its object. This time, the name of the destructor starts with a tilde.

To create your own destructor, in the header file, type ~ followed by the name of the object. Here is an example:

//---------------------------------------------------------------------------

#ifndef BricksH

#define BricksH



//---------------------------------------------------------------------------

class TBrick

{

public:

     TBrick();

     TBrick(double L, double h, double t);

     TBrick(const TBrick &Brk);

     ~TBrick();

    double  getLength() const;

    void  setLength(const double l);

    double  getHeight() const;

    void  setHeight(const double h);

    double  getThickness() const;

    void  setThickness(const double t);

    double  CementVolume();

    void  ShowProperties();

private:

    double Length;

    double Height;

    double Thickness;

};

//---------------------------------------------------------------------------

#endif

As done with a default constructor, you don't need to put anything in the implementation of a destructor. In fact, when a program terminates, the compiler can itself destroy all of the objects and variables that your program has used. The only true time you will be concerned with destroying objects is if the objects were created dynamically, which we will learn when studying pointers.

You can implement your destructor in the header file by just providing it with empty parentheses:

//---------------------------------------------------------------------------

#ifndef BricksH

#define BricksH



//---------------------------------------------------------------------------

class TBrick

{

public:

    ...

     ~TBrick() {}

    ...

private:

    ...

};

//---------------------------------------------------------------------------

#endif

Otherwise, you can also implement it in the cpp file with empty parentheses. Here is an example:

//---------------------------------------------------------------------------

 TBrick::~TBrick()

{

}

//---------------------------------------------------------------------------

Using Destructors

  1. To illustrate the construction and destruction effects of an object, create a new Console Application named Library
  2. Change the content of the file as follows:
     
    //---------------------------------------------------------------------------
    
    #include <iostream>
    
    using namespace std;
    
    //---------------------------------------------------------------------------
    
    class TBook
    
    {
    
    public:
    
        TBook(); // Constructor
    
        ~TBook(); // Destructor
    
        void Message() { cout << "\tI read the book\n"; }
    
    };
    
    //---------------------------------------------------------------------------
    
    TBook::TBook()
    
    {
    
        cout << "I see a book... Using the Constructor\n";
    
    }
    
    //---------------------------------------------------------------------------
    
    TBook::~TBook()
    
    {
    
        cout << "I close the book! Using the Destructor\n";
    
    }
    
    //---------------------------------------------------------------------------
    
    int main()
    
    {
    
        cout << "I am at the library\n";
    
        {
    
            TBook A;
    
        }
    
    
    
        cout << "\nI didn't like that book. I will try another\n\n";
    
        {
    
            TBook B;
    
            B.Message();
    
        }
    
    
    
        cout << "\nI am getting out of the library\n\n";
    
    
    
        
    
        return 0;
    
    }
    
    //---------------------------------------------------------------------------
  3. Execute the program to see the result:
     
    I am at the library
    
    I see a book... Using the Constructor
    
    I close the book! Using the Destructor
    
    
    
    I didn't like that book. I will try another
    
    
    
    I see a book... Using the Constructor
    
            I read the book
    
    I close the book! Using the Destructor
    
    
    
    I am getting out of the library

  4. Return to your programming environment

  5. Reopen the Students project from the Students2 folder.

  6. To create a destructor for our TStudent class, change the header file as follows:
     
    //---------------------------------------------------------------------------
    
    #ifndef StudentsH
    
    #define StudentsH
    
    #include <iostream> 
    
    using namespace std;
    
    //---------------------------------------------------------------------------
    
    class TStudent
    
    {
    
    public:
    
         TStudent();
    
         TStudent(string F, string L);        // Name Initializer
    
         TStudent(int DOB, int MOB, int YOB); // Initial Date of birth
    
         TStudent(string fn, string ln,
    
                            int DOB, int MOB, int YOB);
    
         ~TStudent();
    
         TStudent(const TStudent& S);
    
        void  Display();
    
    private:
    
        string FirstName;
    
        string LastName;
    
        int DayOfBirth;
    
        int MonthOfBirth;
    
        int YearOfBirth;
    
    };
    
    //---------------------------------------------------------------------------
    
    #endif

  7. Implement the destructor in the Students.cpp file as follows:
     
    //---------------------------------------------------------------------------
    
     TStudent::~TStudent()
    
    {
    
    }
    
    //---------------------------------------------------------------------------

  8. Test the program and return to your programming environment.

 
 

Previous Copyright © 2000-2004 FunctionX, Inc. Next