C++ – Class Constructors

In C++, class constructors are special kind of methods to instantiate a class. When class’s object is going to create, C++ will first call class’s constructor to initialize the class. Initialize the class means, assigning it’s members and allocating any dynamic memory etc., After class’s constructor is called, class’s object creation will be completed.

Constructors with or without arguments

Constructors can be created with or without any arguments. If the constructor created without any arguments, we can call that constructor, a default constructor. If we do not create a default constructor, compiler will automatically creates a default constructor for us.

Note that, constructors do not have any return type.

Name of the constructor should be the same as the name of the class. Otherwise, compiler will treat it as a method of the class, and it can not be called during the creation of the class object.

We can pass a single or multiple arguments to the class constructor. Here is an example;

#include <iostream>

using namespace std;

class Shape
{
public:
	Shape()
	{
		cout << "This is default constructor." << endl;
	}

	Shape(int a)
	{
		cout << "Construtcor with a single argument (" << a << ")." << endl;
	}

	Shape(char text[], int b, char c)
	{
		cout << "Construtcor with multiple arguments (" << text << "," << b << "," << c << ")." << endl;
	}
};

int main()
{
	Shape shape;
	Shape shape1(100);
	Shape shape2("Hello!", 10, 65);

	return 0;
}

The Shape class has three constructors. One is default constructor, second one is the constructor with single argument and another one is multiple argument constructor. In main method, it shows how to create a class’s instances using these constructors. You will come to know how it executes, when you compile and run the code.

As mentioned above, constructors are special kind of methods to the class. In case of inheritance, the constructors are not inherited to the class’s derived classes. So, you can’t overload or override one class’s constructor in another class (derived class).

If you don’t specify any constructor for a class, C++ automatically creates one for you. See the below code:

#include <iostream>

using namespace std;

class Pet
{
public:
	void Display()
	{
		cout << "Pet" << endl;
	}
};

int main()
{
	Pet pet;
	pet.Display();

	return 0;
}

Check the above code. It doesn’t have the constructor explicitly declared. But C++ compiler provides a constructor implicitly. That is the reason, allows to create a Pet class object and allowed to call it’s method, Display.
..

Add a Comment

Your email address will not be published.