C++ Constructors

 

C++ Constructors

 

A constructor is a special member function with the same name as the class. The constructor doesn’t have a return type. Constructors are used to initialize the objects of their class. Constructors are automatically invoked whenever an object is created. 

Characteristics of Constructors in C++

  • A constructor should be declared in the public section of the class.
  • They are automatically invoked whenever the object is created.
  • They cannot return values and do not have return types.
  • It can have default arguments.

 

An example of how a constructor is used is,

#include <iostream>
using namespace std;
 
class Employee
{
 
public:
    static int count; //returns number of employees
    string eName;
 
    //Constructor
    Employee()
    {
        count++; //increases employee count every time an object is defined
    }
 
    void setName(string name)
    {
        eName = name;
    }
 
    static int getCount()
    {
        return count;
    }
};
 
int Employee::count = 0; //defining the value of count
 
int main()
{
    Employee Harry1;
    Employee Harry2;
    Employee Harry3;
    cout << Employee::getCount() << endl;
}


Output:

3

 

Parameterized and Default Constructors in C++

Parameterized constructors are those constructors that take one or more parameters. Default constructors are those constructors that take no parameters. This could have helped in the above example by passing the employee name at the time of definition only. That should have removed the setName function.

 

Constructor Overloading in C++

Constructor overloading is a concept similar to function overloading. Here, one class can have multiple constructors with different parameters. At the time of definition of an instance, the constructor, which will match the number and type of arguments, will get executed.

 

For example, if a program consists of 3 constructors with 0, 1, and 2 arguments and we pass just one argument to the constructor, the constructor which is taking one argument will automatically get executed. 

 

Constructors with Default Arguments in C++

Default arguments of the constructor are those which are provided in the constructor declaration. If the values are not provided when calling the constructor the constructor uses the default arguments automatically. 

 

An example that shows declaring default arguments is

class Employee
{
 
public:
    Employee(int a, int b = 9);
};

 

Copy Constructor in C++

A copy constructor is a type of constructor that creates a copy of another object. If we want one object to resemble another object we can use a copy constructor. If no copy constructor is written in the program compiler will supply its own copy constructor. 

 

The syntax for declaring a copy constructor is


class class_name
{
    int a;
 
public:
    //copy constructor
    class_name(class_name &obj)
    {
        a = obj.a;
    }
};