What is default constructor in C++? – Availability Discussion

Default constructor in C++ is provided by the compiler if we don’t implement any constructor in the class. For example, in below class, we don’t have any constructor implemented.

Hence, once we create an object of the class then default constructor is called in C++ program provided by the compiler internally.

class A{
public:
	void display(){
		cout<<"A::display";
	}

};
int main(){

	//On object creation default constructor
	//will be called provided by compiler.
	A ob;
	ob.display();

	return 0;
}

NOTES:

People also refer an empty constructor implemented in a class as a default constructor in C++. For example, in below class A () {} is an empty constructor with no parameter. You can read if an empty constructor in C++ programs is necessary to write or not.

class A{
public:
	A(){} //Empty constructor
	
	void display(){
		cout<<"A::display";
	}
};

Interviewer: Will default constructor provided by compiler if we overload 1 or 2 argument constructor in a class?

No.If we have overloaded one or more arguments constructor (parameterized constructor in C++ class) then compiler will not provide default constructor for the class. So, if we create object that is supposed to call default or empty constructor, will not be available and compiler will give error. for example, in below class, we don’t have default constructor, so if we create object like A ob; compiler will flash an error that default constructor is not available.

So, to resolve the error, we need to write an empty constructor i.e. A () {} in the class. If you think that we will always create an object with 1 parameter that will call 1 argument overloaded constructor, then no need to write empty constructor.

class A{
	int a;
public:
	A(int b):a(b)
	{		
	} 	
	
};
int main(){
	// this will give compiler error as no
	//default or empty constructor is available.
	A ob;

	return 0;
}

Interviewer: Is default constructor by compiler for C++ program called if we write copy constructor in a class?

No, If we write a copy constructor in the class then default constructor will also not be available.

Related Posts