Calling Default Constructor with Empty Brackets
To call a default constructor with empty brackets, we can explicitly define a constructor with no parameters, which will serve as the default constructor and then we can call the default constructor with empty brackets.
C++ Program to Call Default Constructor with Empty Brackets
The following program illustrates how we can call a default constructor with empty brackets in C++.
// C++ Program to Call Default Constructor with Empty
// Brackets
#include <iostream>
using namespace std;
class MyClass {
public:
// Default constructor with empty brackets
MyClass()
{
cout << "Default constructor called." << endl;
}
// Constructor with parameters
MyClass(int value)
{
cout << "Constructor with parameter called. Value: "
<< value << endl;
}
};
int main()
{
// Call the default constructor
// Declare an instance of the class and the default
// consttrcutor will be called automatically
MyClass obj;
return 0;
}
Output
Default constructor called.
Time Complexity: O(1)
Auxiliary Space: O(1)
Why Can’t the Default Constructor Be Called with Empty Brackets?
In C++, the default constructor is a constructor that has no arguments or default value for all the arguments. If we don’t explicitly define a default constructor, the compiler generates a default constructor during compilation. In this article, we will learn why can’t the default constructor be called with empty brackets in C++.
Contact Us