What is default constructor in C++ with examples?
In this chapter of C++ interview questions, we will learn about:
-
what is default constructor in c++?
-
syntax of default constructor in c++
-
example of default constructor in c++
What is default constructor in c++?
A constructor that does not take any argument and has no parameters is known as a default constructor in C++.
For the initialization of an object, default constructor is a must need. If a constructor is not defined explicitly by programmar. No problem :)
The compiler will provide one default constructor internally if it is needed.
Syntax of default constructor in c++
class class_name(parameter 1, parameter 2, parameter 3, ....)
{
//define a constructor, or
//default constructor will be provided by compiler
}
In above syntax since we have not defined constructor ourself so it will be provided implicitly by compiler.
Next, in below example, we will see example of constructor in c++ where no parameter constructor will be created by user.
Example of default constructor in C++
Default constructor in c++ example program is shown below:
class Line
{
public:
int size;
//default constructor
Line()
{
size=15;
}
};
int main()
{
//default constructor called when object is created
Line l;
cout<<"Line size is"<<" "<<l.size<<" "<<"cm";
return 0;
}
Output
Line size is 15 cm
For the Above code as soon as the object is created, a constructor is called for initializing its data members.
In above case, we have provided the no parameter default constructor Line() { } but if we don't provide one then it will be provided by compiler in such case to help initialize the data members.
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Page Views :
Published Date :
Feb 06,2021