C++: Class Constructors

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

Constructors don’t have any return type. But can take multiple arguments. If the constructor have no arguments means, it is a default constructor. Name of the constructor should be same as the name of the class; if the names are different means, you are creating a method for the class; not the constructor.

Check the below 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 have three constructor. One is default constructor, second one is constructor with single argument and another one is multiple argument constructor. In main, 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 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 its method Display.
..

Leave a Reply