C++ Constructors

Drishtant Regmi
6 min readJun 26, 2020

--

In this article, we’ll learn about constructors, why and how there’re used, and the types of constructors in C++ with appropriate examples.

Photo from Alphacoders

What is a constructor?

A constructor is a special method of a class that initializes data members of an object. It is automatically invoked for each object.

In Object-Oriented Programming, a constructor is always public, usually has the same name as the class, and has no return type.

Let us consider a simple class with a constructor.

#include <iostream>
using namespace std;
class Example
{
public: //Access Specifier
Example() // Constructor
{
cout << "I am in a constructor"; //Body of the constructor
}
};
int main()
{
Example ExampleObject; // Create an object(ExampleObject) of
//class(Example), which will call the
//constructor.
return 0;
}

Class: Example
Constructor: Example()
Object of class: ExampleObject

The given program has a class called Example, meaning its constructor has the same name(Example()) as the class. When an object(ExampleObject) is called out in the main function, the constructor is automatically invoked and gives the output as shown:

I am in a constructor

Constructors can also be defined outside a class, using class name and scope resolution operator(::).

#include <iostream>
using namespace std;
class Example
{
public:
Example(); // Constructor declaration
};
Example::Example() // Constructor Definition
{
cout << "I am in a constructor"; //Body of the constructor
};
int main()
{
Example ExampleObject;
return 0;
}

This will give an output identical to the first program.

I am in a constructor

When an object is created, one of its constructors is executed. However, if there’s no constructor present, the compiler will generate one that does not take any argument.

Parameters in a Constructor

A parameter is a special kind of variable used to pass arguments to a class or a function. Constructors can take parameters like how a regular function does, which is essential for setting initial values.

#include <iostream>
using namespace std;
class Player
{
public: // Access specifier
string name; // Attribute
string club; // Attribute
int age; // Attribute
//Constructor with parameters
Player(string x, string y, int z): name(x), club(y), age(z){}
};int main()
{
Player p1("Messi", "Barcelona", 33); //Object for Constructor
Player p2("Ronaldo", "Juventus", 35); //Object for Constructor
// Printing values
cout << p1.name<< " " << p1.club << " " << p1.age << "\n";
cout << p2.name<< " " << p2.club << " " << p2.age << "\n";
return 0;
}

The given program’s class has name, club, and age attributes along with a constructor having parameters. In the main function, we create the object of the class and call the constructor. We also pass the corresponding values to the constructor, so the values get initialized to the variable defined.

Output:
Messi Barcelona 33
Ronaldo Juventus 35

We often see data members being initialized inside the constructor’s body like the one below. This isn’t the best practice.

// Not the best practice!
fruit()
{
name="apple"
}

Why are constructors used?

Constructors are used for the initialization of data members that are important for methods to know early. For example: If we have an object for a circle, then it’s vital we have the radius known during the time of initialization for other methods like ShowArea() to operate with minimum errors. A constructor would initialize the value and make sure that the data is valid during the time of method execution.

#include <iostream>
using namespace std;
class Area
{
private:
int radius;
public:
Area(): radius(10.0){ } //Constructor
void FindRadius()
{
cout << "Enter radius: ";
cin >> radius;
}
float FindArea()
{
return (3.14 * radius * radius);
}
void ShowArea(float rad)
{
cout << "Area of circle with user input: " << rad;
};
int main()
{
Area A1, A2;
float rad;
A1.FindRadius();
rad = A1.FindArea();
A1.ShowArea(rad);
cout << endl << "Area of circle when radius is automatically
initialized: ";
rad = A2.FindArea();
A2.ShowArea(rad);
return 0;
}

In the given program, objects A1 and A2 are created for class Area. Then, FindRadius() function is called which asks the radius from the user. Showarea() prints the area of circle whose radius is given by the user.

In the next case, the value assigned from the constructor (radius=10) is taken as the radius, and the area is printed accordingly.

Enter radius: 5
Area of circle with user input: 78.5
Area of circle when radius is automatically initialized: 314

Best Practise: Always provide default values for members!

Types of C++ Constructors

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor

Default Constructor

A default constructor takes no arguments. They usually have no parameters. However, they can have parameters with default values.

The first program is also an example of default constructor.

#include <iostream>
using namespace std;
class Year
{
public:
int date;

Year(): date(2020) {} //Default Constructor
};
int main()
{
Year y; //Object for constructor
cout << y.date;
}

The given class Year has a default constructor which when called, sets the date value to 2020. When the variable date of class year is called and printed out, it gives the output as follows:

2020

Parameterized Constructor

As the name suggests, these are constructors with parameters. By passing the necessary values, we can assign different values to data members of different objects.

The program shown in “Parameters in a constructor” is a parameterized constructor

#include <iostream>
using namespace std;
class Player
{
public: // Access specifier
string name; // Attribute
Player(string x): name(x) {} // Constructor with parameter
};
int main()
{
Player p1("Messi"); //Object for Constructor
Player p2("Ronaldo");
Player p3("Bale");
// Print values
cout << p1.name<<"\n";
cout << p2.name<<"\n";
cout << p3.name<<"\n";
return 0;
}

In this program, the parameter of the constructor is a string that carries the name of a player. When the value is passed, the string is assigned to the variable defined.

Output:
Messi
Ronaldo
Bale

Copy Constructor

A constructor that is used to create copies of an existing object of a class is a copy constructor.

For a class ‘Example’ with a constructor ‘Example()’ and predefined object ‘E1’, we can create an object E2 that is an exact copy of object E1 as:

class Example
{
Example()
{
cout<<"Object E1"
}
}
int main()
{
Example E1;
Example E2(A1);
//OR
Example E2 = E1; //Copies content of E1 to E2 if there is any
}

Here, the object E2 contains the same values as that of object E1. This makes it easier in times when there is a necessity to duplicate values since all classes by default have a copy constructor built.

Constructor Overloading in C ++

Similar to other member functions, constructors can also be overloaded in C++. We are having overloaded constructors when we have a default constructor and a parameterized constructor defined in our class where one has a parameter and the other doesn’t.

Constructors can also be overloaded by having more than one constructor that are differentiated by the parameters they have.

#include <iostream>
using namespace std;
class Player
{
public:
int no;
string name;
// first constructor
Player(int x): no(x)
{
name = "None";
cout<<no<<" "<<name;
}
// second constructor
Player(int x, string str): no(x), name(str)
{
cout<<endl<<no<<" "<<name;
}
};
int main()
{
// Player P1 initialized with no 105 and name None
Player P1(105);

// Player P2initialized with roll no 11 and name Bale
Player P2(11, "Bale");
}

In the program above, there are two constructors present with different parameters, thus overloading the constructors.

Output:
105 None
11 Bale

When we define any constructor explicitely without defining a default constructor, the compiler will not provide default constructor automatically. In such case, we will have to define default constructor on our own if it is needed.

--

--