Default constructor in C++
What is default constructor ?
On this page we will discuss about default constructor in C++. A constructor is a special type of member function that is automatically called when the object of the class is created. The name of the constructor is the same as the name of the class and it does not have any return type.There are three types of constructor in C++
- Default constructor
- Parameterized constructor
- Copy constructor
Default constructor in C++
The default constructor is a constructor that has no parameters, and even if it has parameters then all the parameters have default values. If we had not defined any constructor in the program then the compiler automatically creates one default constructor during the time of object call. This constructor which is created by the compiler implicitly does not have any parameters. As there are no arguments in the default constructor it is also known as “zero-argument constructor“. The default constructor can be declared both inside and outside the class.
Syntax for declaring default constructor inside the class
class class_name { public: class_name(); //default constructor declared. };
Syntax for declaring default construct outside the class
class class_name { }; class_name :: class_name() //default constructor declared. { }
Example 1 : Program to demonstrate default constructor
#include <iostream> using namespace std; class PrepInsta { public: PrepInsta() //Default constructor. { cout<<"Learning is fun with PrepInsta"<<endl; } }; int main() { PrepInsta obj;//Creating object to invoke default constructor. return 0; }
Output:
Learning is fun with PrepInsta
Example 2:
#include <iostream> using namespace std; class Base { public: int square; Base (int x = 6) //default constructor with default value { square = x * x; } void show () { cout << "Square of number =" << square << endl; } }; int main () { Base b; b.show (); return 0; }
Output:
Square of number =36
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment