C++ Default Constructor
A default constructor is such constructor which does not take any parameter. A constructor initializes the data member when a class object created.
If a programmer does not create any constructor explicitly, then C++ compiler implicitly creates a default constructor and initialize data member with its default value.
Syntax:
className(){
// Constructor definition
}
C++ Default Constructor Example 1
Creating a class with the name '
Employee' and a default constructor '
Employee()' which initialize data member '
id'.
#include <iostream>
using namespace std;
class Employee
{
int id;
public:
Employee(){
id=101;
}
void display(){
cout<<id;
}
};
int main(){
Employee emp;
emp.display();
return 0;
}
Output:
C++ Default Constructor (Implicit) Example 2
In this example compiler itself internally (implicit) create default constructor and initialize the value to a data member.
#include<iostream>
#include<string>
using namespace std;
class Employee
{
int id;
string name;
public:
int ph;
void display(){
cout<<"id="<<id<<endl;
cout<<"name="<<name<<endl;
}
};
int main(){
Employee emp;
emp.display();
cout<<"ph="<<emp.ph<<endl;
return 0;
}
Output:
Expected Output
Garbage value Output
Some time default implicit constructor initialize garbage value to a data member.