Open In App

How to Define the Default Constructor in C++?

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a constructor that takes no parameters is called a default constructor. A default constructor gets automatically invoked when an object of a class is created without any arguments. It is mainly used to initialize legal initial values to the member variables or perform other setup tasks.

In this article, we will look at how to define a default constructor in C++

Defining a Default Constructor in C++

To define a default constructor explicitly, you must create a member function with the same name as the class with no parameters. In simple terms, the default constructor is defined like any other constructor but without parameters.

Syntax to Define a Default Constructor

class ClassName { 
public:
ClassName();
// Other class members
};

C++ Program to Define a Default Constructor

C++




// C++ program to define a Default constructor
  
#include <iostream>
using namespace std;
  
class MyClass {
public:
    // Default constructor
    MyClass() { cout << "Default constructor called\n"; }
};
  
int main()
{
    // Creating an object of MyClass
    MyClass obj;
  
    return 0;
}


Output

Default constructor called

Explanation: In the above example, We have “MyClass” that has a default constructor. When an object of MyClass is created then the default constructor is invoked. We can also write initialization code inside the default class “MyClass”.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads