CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

C++ – Class Constructors

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

Constructors with or without arguments

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

Note that, constructors do not have any return type.

The name of the constructor should be the same as the name of the class. Otherwise, the 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 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 the default constructor, the second one is the constructor with a single argument and the other one is the 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 kinds of methods for the class. In the case of inheritance, the constructors are not inherited by 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 the C++ compiler provides a constructor implicitly. That is the reason, allows to the creation of a Pet class object and is allowed to call its method, Display.
..

C++ – Class Constructors

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top