Default constructor in C++

Default constructor in C++

What is default constructor in C++?

A constructor is a special type of member function that is automatically called when the object of the class is created. The name of the constructor is the same as the name of the class and it does not have any return type.

There are three types of constructor in C++

  • Default constructor
  • Parameterized constructor
  • Copy constructor

In this article, we will learn more about default constructor in C++.

Default constructor in C++

The default constructor is a constructor that has no parameters, and even if it has parameters then all the parameters have default values. If we had not defined any constructor in the program then the compiler automatically creates one default constructor during the time of object call. This constructor which is created by the compiler implicitly does not have any parameters. As there are no arguments in the default constructor it is also known as “zero-argument constructor“. The default constructor can be declared both inside and outside the class.

Syntax for declaring default constructor inside the class

class class_name
{
    public:
    class_name(); //default constructor declared. 
};

Syntax for declaring default construct outside the class

class class_name
{
   
};
class_name :: class_name() //default constructor declared.
{
      
}

C++ program to demonstrate default constructor

#include <iostream>
using namespace std;
class PrepInsta
{
public:
   PrepInsta() //Default constructor.
   {
      cout<<"Learning is fun with PrepInsta"<<endl;
   }
};
int main()
{
   
   PrepInsta obj;//Creating object to invoke default constructor.
   
   return 0;
}
Output:
Learning is fun with PrepInsta