Default Constructors in C++
Last Updated :
06 Aug, 2025
In C++, a constructor is a special member function that is automatically called when an object of the class is created. Among different types of constructors, a default constructor is the one that takes no arguments.
It plays a crucial role in object initialization when no specific data is provided. If you do not explicitly define any constructor in your class, the C++ compiler automatically provides a default constructor.
What is a Default Constructor?
A default constructor is a constructor that can be called with no parameters. It is either defined explicitly by the programmer or implicitly generated by the compiler.
Example 1: No User Defined Constructor:
In the above class, a default constructor will be generated by the compiler at compile time.
class GFG{
public:
};Example 2: Explicitly Defined Default Constructor:
class GfG {
public:
// Default Constructor i.e. constructor
// with no arguments
GfG() {}
};In the above class, as programmer defined a constructor with no argument (default constructor), so no compiler generated default constructor will be needed.
Exanple 3:Default Constructor with Initialization:
You can also initialize class members inside the default constructor.
class GFG {
int x;
public:
GFG() {
x = 10;
cout << "x initialized to " << x << endl;
}
};Use Cases of Default Constructor:
- Creating arrays or vectors of objects
- Needed when using STL containers (like
vector<Class>) - Used when objects need to be initialized to default values
- Required in generic programming and templates
C++
#include <iostream>
using namespace std;
class GFG {
string name;
int roll;
public:
// Default constructor
GFG() {
name = "Unknown";
roll = -1;
cout << "Default constructor called\n";
}
void display() {
cout << "Name: " << name << ", Roll: " << roll << endl;
}
};
int main() {
GFG s1; // Calls default constructor
s1.display();
return 0;
}
OutputDefault constructor called
Name: Unknown, Roll: -1
Explore
C++ Basics
Core Concepts
OOP in C++
Standard Template Library(STL)
Practice & Problems