Horje
How to Define the Default Constructor in C++?

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”.




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Remove Duplicates from a Vector in C++? How to Remove Duplicates from a Vector in C++?
How to Catch Floating Point Errors in C++? How to Catch Floating Point Errors in C++?
Logging System in C++ Logging System in C++
How to Compare Float and Double While Accounting for Precision Loss? How to Compare Float and Double While Accounting for Precision Loss?
How to Insert Pairs into a Map in C++? How to Insert Pairs into a Map in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
11