Default Constructor in C++
A default constructor is a constructor that doesn’t take any argument. It has no parameters. It is also called a zero-argument constructor.
Syntax of Default Constructor
className() {
// body_of_constructor
}
Examples of Default Constructor
The below examples demonstrate how to use the default constructors in C++.
Example 1:
CPP
// C++ program to illustrate the concept of default // constructors #include <iostream> using namespace std; class construct { public : int a, b; // Default Constructor construct() { a = 10; b = 20; } }; int main() { // Default constructor called automatically // when the object is created construct c; cout << "a: " << c.a << endl << "b: " << c.b; return 1; } |
a: 10 b: 20
Note: Even if we do not define any constructor explicitly, the compiler will automatically provide a default constructor implicitly.
Example 2:
C++
// C++ program to demonstrate the implicit default // constructor #include <iostream> using namespace std; // class class student { int rno; char name[50]; double fee; public : }; int main() { // creating object without any parameters student s; return 0; } |
Output
(no output)
As we can see, we are able the object of class student is created without passing any argument even when we haven’t defined any explicit default constructor for it.
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time of object creation. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor.
- Constructor is a member function of a class, whose name is the same as the class name.
- Constructor is a special type of member function that is used to initialize the data members for an object of a class automatically when an object of the same class is created.
- Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as a constructor.
- Constructors do not return value, hence they do not have a return type.
- A constructor gets called automatically when we create the object of the class.
- Constructors can be overloaded.
- A constructor can not be declared virtual.