In C++, a constructor is a special member function that is automatically called when an object of the class is created.
- A default constructor is the one that takes no arguments. It is either defined explicitly by the programmer or implicitly generated by the compiler.
- If you do not explicitly define any constructor in your class, the C++ compiler automatically provides a default constructor.
Example 1: No User Defined Constructor
In the below class, a default constructor will be generated by the compiler at compile time.
class GFG {
public:
};
Example 2: Explicitly Defined Default Constructor
In this example, a constructor with no parameters is explicitly defined. Since a constructor already exists, the compiler will not generate one.
class GFG {
public:
GFG() {
// default constructor
}
};
Objects of this class can be created without arguments.
Example 3: Default Constructor with Initialization
You can also initialize class members inside the default constructor.
#include <iostream>
using namespace std;
class GFG {
int x;
public:
GFG() {
x = 10;
cout << "x initialized to " << x << endl;
}
};
Explanation:
- The default constructor initializes the data member x.
- It runs automatically at object creation time.
- Useful for setting initial default values.
Complete Example
#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;
}
Output
Default constructor called Name: Unknown, Roll: -1
Explanation
- s1 is created without arguments.
- The default constructor initializes name and roll.
- display() prints the initialized values.
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