C++. Class constructor. Features of use constructors in the classes. The default constructor. Parameterized constructors. Examples of classes that contain constructors

C++. Classes. Part 2. Class constructor. Features of use constructors in the classes. The default constructor. Parameterized constructors. Examples of classes that contain constructors

In this topic, the concept of a constructor is considered with the example of unmanaged (native) classes. The materials of this topic also concern the constructors of managed classes.


Contents


1. What is called a class constructor? What is the purpose of class constructor?

A class can contain special functions: constructors and destructors. A class constructor is a special method (function) of a class. The constructor is called when a class object is created. Typically, the constructor is used for:

  • allocating memory for a class object;
  • initial initialization of the internal data of the class.

The constructor is intended to form an instance of a class object. The name of the class constructor is the same as the class name.

2. At what point does the program call the class constructor?

The constructor is called when a class object is created. The class constructor is called by the compiler.

3. Can the constructor have parameters? Examples of constructors with different number of parameters

The constructor can have any number of parameters. Also, the constructor can be without parameters (the default constructor).

An example. A CMyDate class is declared that specifies the date (day, month, year). Two constructors are declared in the class. One constructor with no parameters. Another constructor gets three parameters that set a new date. Declaring a class and its methods has the form

// class that defines the date
class CMyDate
{
    int day;
    int month;
    int year;

    public:
    // class constructors
    CMyDate(); // constructor without parameters
    CMyDate(int d, int m, int y); // constructor with 3 parameters

    // class methods
    void SetDate(int d, int m, int y); // set a new date
    int GetDay(void); // returns day
    int GetMonth(void); // returns month
    int GetYear(void); // returns year
};

// implementation of class constructors and methods
// constructor without parameters (default constructor)
CMyDate::CMyDate()
{
    // set the date 01.01.2001
    day = 1;
    month = 1;
    year = 2001;
}

// constructor with 3 parameters
CMyDate::CMyDate(int d, int m, int y)
{
    day = d;
    month = m;
    year = y;
}

// set a new date
void CMyDate::SetDate(int d, int m, int y)
{
    day = d;
    month = m;
    year = y;
}

// return day
int CMyDate::GetDay(void)
{
    return day;
}

// return month
int CMyDate::GetMonth(void)
{
    return month;
}

// retutn year
int CMyDate::GetYear(void)
{
    return year;
}

Demonstration of calling constructors when declaring objects of a class

CMyDate MD1; // the constructor without parameters is called
CMyDate MD2(4, 5, 2008); // constructor is called with three parameters

int t;
t = MD1.GetDay(); // t = 1
t = MD1.GetYear(); // t = 2001
t = MD2.GetMonth(); // t = 5
t = MD2.GetYear(); // t = 2008

 

4. Is it necessary to declare a constructor in a class?

Not. When you create a class object that does not contain any constructors, the implicit default constructor will be called. This constructor allocates memory for the class object. However, in the class, you can declare your own default constructor. This constructor is called: an explicitly defined default constructor.

 

5. What is the default constructor? Examples

The default constructor is the constructor of a class that is declared without parameters. If the class does not explicitly contain a specific constructor, then when the object is created, the default constructor is automatically called. When declaring a class object, the class constructor simply allocates memory for it.

Example 1. Let the class CMyPoint defining the point on the coordinate plane be given. The class does not implement any constructors.

// A class that defines a point on the coordinate plane
class CMyPoint
{
    int x;
    int y;

    public:
    // class methods
    void SetPoint(int nx, int ny)
    {
        x = nx;
        y = ny;
    }

    int GetX(void) { return x; }
    int GetY(void) { return y; }
};

However, when you create a class object, the compiler automatically calls the default constructor.

CMyPoint MP; // the default constructor is automatically called

MP.SetXY(4, -10); // call of class methods
int t;
t = MP.GetY(); // t = -10

The default constructor will automatically be called only if nothing constructors are declared in the class. Once you declare any other constructor with parameters in the class, then when you declare

CMyPoint MP;

the compiler will generate an error.

Example 2. Modification of the CMyPoint class. The class has an explicit default constructor.

// A class that defines a point on the coordinate plane
class CMyPoint
{
    int x;
    int y;

    public:
    // the explicit default constructor
    CMyPoint()
    {
        x = y = 0;
    }

    // class methods
    void SetPoint(int nx, int ny)
    {
        x = nx;
        y = ny;
    }

    int GetX(void) { return x; }
    int GetY(void) { return y; }
};

Demonstration of a call to an explicitly defined default constructor

CMyPoint MP; // It will be called an explicit default constructor
int t;
t = MP.GetX(); // t = 0

 

6. How many default constructors can have class?

Each class can have only one default constructor. This is due to the fact that there can not be two methods (functions) in the class with the same signature.

7. Can the constructor return a value?

The constructor can not return values (even the value of void). If you write a return value in the constructor using the ‘return’ statement, the compiler will generate an error.

 

8. An example of declaring and using a class that contains several constructors. Implementation of ‘string’ type in a class

For example, you need to declare a class that contains information about the employee’s name and his age. To represent internal data members in a class, the ‘string’ type is used. To use the string type in Visual C ++ programs, you need to connect the <string> library and the std namespace at the beginning of the module that implementes the class,

#include <string>
using namespace std;

Class declaration

// A class that defines general customer data
class CName
{
    string name; // Name
    string surname; // Surname
    string patronymic; // Patronymic
    int age; // age

    public:
    CName(void); // constructor without parameters
    CName(string n_name, string n_sname); // constructor with two parameters
    CName(string n_name, string n_sname, string n_patr); // constructor with three parameters
    CName(string n_name, string n_sname, string n_patr, int n_age); // four parameters

    // internal class methods - implemented in the class declaration
    string GetName(void) { return name; }
    string GetSurname(void) { return surname; }
    string GetPatr(void) { return patronymic; }
    int GetAge(void) { return age; }

    ~CName(void); // destructor
};

Implementing class constructors and destructor

// Implementing class constructors and destructor
// constructor without parameters
CName::CName(void)
{
    name = "";
    surname = "";
    patronymic = "";
    age = 0;
}

// constructor with two parameters
CName::CName(string n_name, string n_sname)
{
    name = n_name;
    surname = n_sname;
    patronymic = "";
    age = 0;
}

// constructor with 3 (three) parameters
CName::CName(string n_name, string n_sname, string n_patr)
{
    name = n_name;
    surname = n_sname;
    patronymic = n_patr;
    age = 0;
}

// constructor with 4 (four) paremeters
CName::CName(string n_name, string n_sname, string n_patr, int n_age) // four parameters
{
    name = n_name;
    surname = n_sname;
    patronymic = n_patr;
    age = n_age;
}
// destructor
CName::~CName(void)
{
}

9. How does the class constructor work in the case when an object of another class (subobject) is declared in the class? Example

In this case:

  • first of all, the constructor (constructors) of the class that is the subobject of the inner class is called;
  • next, the constructor of the outter class is called.

Example. Let there be 2 classes: CMyPoint, CMyLine. In the CMyLine class, there are two subobjects of the CMyPoint class. When creating an object of the CMyLine class, first of all, two CMyPoint class constructors will be called for two subobjects, and then a CMyLine class constructor will be called.

// CMyPoint class
class CMyPoint
{
    int x, y;

    public:
    CMyPoint(void); // class constructor
};

// constructor of CMyPoint class
CMyPoint::CMyPoint(void)
{
    // ...
}

// CMyLine class
class CMyLine
{
    CMyPoint p1;
    CMyPoint p2;

    public:
    CMyLine(void);
};

// constructor of CMyLine class
CMyLine::CMyLine(void)
{
    // ...
}

Declaring an object of the CMyLine class

CMyLine ML; // following order: 1 - two CMyPoint() constructors, 2 - CMyLine() constructor

After this declaration, the constructors will be called in the following order:

  • CMyPoint::CMyPoint() for object p1 of class CMyLine;
  • CMyPoint::CMyPoint() for object p2 of class CMyLine;
  • CMyLine::CMyLine() for object ML.

 

10. How does the constructor of a class work in the case where a class object is created that is derived (inherited) from another class?

If there are two classes, one of which is basic and the other is inherited from the base class, then the sequence of calls is as follows:

  • first, the base class constructor is invoked;
  • next, the constructor of the inherited class is called.

 

11. Can the constructor be declared in the ‘private’ section?

Yes. This constructor is called a private constructor.

 

12. In which cases can private constructors be declared?

When declaring an ordinary class object, the constructors that are placed in the ‘private’ section are not accessible.

To use private constructors, you must fulfill one of three conditions:

  • the constructor must be called by a static member of the class;
  • the constructor must be called by a friendly class;
  • in the class, a member function is declared that will call this constructor to create a new object.

 

13. How will the program work if you try to create a class object that declares a private constructor by default?

In this case, there will be a compilation error.

For example. Let the class CMyDate be given. The class defines an explicit default constructor (without parameters).

class CMyDate
{
    private:
    // explicit default constructor
    CMyDate()
    {
        // body of the constructor
        // ...
    }
}

An attempt to create a class object will cause in a compilation error

CMyDate MD; // compilation error

The same will happen if you try to create a static object

static CMyDate MDS; // compilation error also for a static object

 

14. Can two constructors be declared in the class that take the same number of parameters?

Yes. However, with the condition that the types of parameters will be different. For a class, the following rule must be satisfied:

  • in a class there can not be two methods (functions) with the same (coincident) signature.

This question is closely related to the topic of function overloading.

15. What constructors are called parametrized?

A parametrized constructor is a class constructor that has parameters.

16. What are the ways to initialize the members of a class object using a constructor that takes one parameter? An example

For a constructor that receives one parameter, there are two initialization methods:

  • initialization on a sample of a function call;
  • initialization on a sample assignment operator.

Example. Let the class, in which one variable n of type int is defined, is given. The class has two constructors. The first is a constructor without parameters, zeroing the value of n. The second is a constructor with one parameter, setting a new value of n.

General view of class declaration

class CMyInt
{
    private:
    int n; // the number of array elements

    public:
    ~CMyInt(void); // destructor
    CMyInt(int nn) { n = nn; } // constructor with one parameter

    // class methods
    void SetN(int nn) { n = nn; }
    int GetN(void) { return n; }
};

You can declare an object of the CMyInt class, using a single parameter constructor, in two ways

// Demonstration of a class object declaration,
// if the class has a constructor with 1 parameter
CMyInt MI1(10); // calling the constructor with 1 parameter
CMyInt MI2 = 20; // the same, but in a different way

int t;
t = MI1.GetN(); // t = 10
t = MI2.GetN(); // t = 20

 


Related topics