Constructors are the special type of methods that get called when we create an instance for a class i.e. an object.

Constructors are used to initialize the member variables of a class with their default values. Without initializing, we cannot access them from outside of a class.

For example, the following program gives you a compilation error because we accessed a class variable without initializing it.

#include <iostream>

class IntrestCalculator {

public:
	int intrestValue;
};

int main() {
	IntrestCalculator obj;
	std::cout << obj.intrestValue;
}

In the below example, interestValue contains a garbage value because it has not been initialized. Inside a class, it is allowed to use class variables without initializing them but it may provide an unexpected result as shown in the below example.

#include <iostream>

class IntrestCalculator {

public:
	// Not initialized & contains a garbage value
	int intrestValue;

	int calculateIntrest(int amount) {
		return (amount * intrestValue) / 100;
	}
};

int main() {

	IntrestCalculator obj;

	// The following line prints a garbage or incorrect value.
	// Because the intrestValue is not defined
	std::cout << obj.calculateIntrest(10000);
}

How to create a constructor?

Constructors can be created in the same way as how we create methods. But we must follow the following rules:

  • The constructor name must be the same as the class name.
  • The constructor should not have a return type.
  • Must be declared under the public access modifier.

Example:

#include <iostream>

class IntrestCalculator {

public:
	int intrestValue;

	// Constructor with no parameters
	IntrestCalculator()
	{
		intrestValue = 2;
	}
	
	int calculateIntrest(int amount) {
		return (amount * intrestValue) / 100;
	}
};

int main() {

	IntrestCalculator obj;
	std::cout << obj.calculateIntrest(10000);
}

Types of constructors

  1. Default constructor
  2. Parameterized constructor
  3. Copy constructor

What is a default constructor?

In the above example, we declared a constructor and we initialized a class variable inside the constructor. We also call it a no-param constructor.

If we don’t create any constructor then by default C compiler provides a default one which is known as a default constructor. It looks like as shown in the below example.

#include <iostream>

class IntrestCalculator {

public:
	int intrestValue;

	// Default constructor
	IntrestCalculator()
	{
		// Does not contain anything inside it.
	}
	
};

int main() {
	IntrestCalculator obj;
}

What is a parameterized constructor?

Using parameterized constructor, we can pass parameters to the constructor as shown in the below example. With this, we can initialize the class members by passing values to the constructor.

#include <iostream>

class InterestCalculator {

public:
	int interestValue;

	// Constructor with one parameter
	InterestCalculator(int interest)
	{
		interestValue = interest;
	}

	int calculateInterest(int amount) {
		return (amount * interestValue) / 100;
	}
};

int main() {

	InterestCalculator obj(2);
	std::cout << obj.calculateInterest(10000);
}

What is a copy constructor?

The copy constructor is nothing but copying the values of one constructor to another constructor. In the copy constructor, we pass the constructor as a parameter.

Programmers must implement logic to copy the required values and if any of the members need dynamic memory then should not point it to the memory of the object passed as a copy. We must re-again allocate memory and assign it to the member.

#include <iostream>

class InterestCalculator {

public:
	int interestValue;

	// Constructor with one parameter
	InterestCalculator(int interest)
	{
		interestValue = interest;
	}

	// copy constructor
	InterestCalculator(InterestCalculator& obj) {
		interestValue = obj.interestValue;
	}

	int calculateInterest(int amount) {
		return (amount * interestValue) / 100;
	}

};

int main() {

	InterestCalculator obj(2);
	std::cout << obj.calculateInterest(10000);
	InterestCalculator obj2(obj);
	std::cout << obj.calculateInterest(10000);

	// The following line prints a garbage or incorrect value.
	// Because the interestValue is not defined
	return 0;
}

Other way to initialize the members in the constructor

#include <iostream>

class InterestCalculator {

public:
    int interestValue;
    int interestDuration;

    InterestCalculator(int interest, duration)
    {
        interestValue = interest;
        interestDuration = duration;
    }

    /* This is equivalent to the above one 
    InterestCalculator(int interest, duration)
        :interestValue(interest), interestDuration(duration){}  
    */
};

Categorized in:

Tagged in: