C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C++ programming language

Default constructor or Zero Argument Constructor with example in C++

Learn: What is the Default Constructor (Zero Argument Constructor) in C++ programming language, how default constructor defines with an Example?

In the last post, we have discussed what the constructor is in C++ programming and what are the types of constructor?

In this post, we are going to learn about default constructors, what are the default constructors, how they define and how they call?

Default Constructor or Zero Argument Constructor

Default constructor is also known as zero argument constructors. Default constructor does not have any parameters and is used to set (initialize) class data members. Since, there is no argument used in it, it is called "Zero Argument Constructor".

In a class, if there is no default constructors defined, then the compiler inserts a default constructor with an empty body in the class in compiled code.

Constructor can also be defined outside of the class; it does not have any return type.

Example:

#include <iostream>
using namespace std;

class Demo
{
	private:
		int A;
		int B;
		int C;
public:
		Demo();
void set(int A, int B, int C);
void print();
};

Demo::Demo()
{
A=1;
B=1;
C=1;
}
		
void Demo::set(int A, int B, int C)
{
 this->A  = A;
 this->B  = B;
 this->C  = C;
}

void Demo::print()
{
cout<<"Value of A :  "<<A<<endl;
cout<<"Value of B :  "<<B<<endl;
cout<<"Value of C :  "<<C<<endl;
}

int main()
{
	Demo obj = Demo(); //Constructor called when object created

	obj.print();
	obj.set(10,20,30);
	obj.print();

	return 0;
}

Output

Value of A :  1
Value of B :  1
Value of C :  1
Value of A :  10
Value of B :  20
Value of C :  30

In above example Demo member function is used as a constructor to initialize data member. And set member function is used set value of data members.





Sponsored Links




COMMENTS