Is C++ Empty Constructor necessary to write in a class?

Answer: C++ Empty constructor necessity  depends upon class design requirements. We know that C++ class constructor is called when we create an object of a class.

If a class is not required to initialize its data member or does not contain data member, there is no need to write empty constructor explicitly. On class object creation, default constructor implicitly called will be enough.

In below class, default constructor will be called on object creation of the class.

class A{

public:
	//No constructor, let default constructor called
	void print(){
	}
};
int main(){
	
	A a;
	a.print();	

	return 0;
}

But, in some of the situations we have to write empty constructor in a class. For example,

Note that if we write any constructor in the class, default constructor by the compiler will not be provided and also, note that default constructor is an empty constructor.

You can read default functions of a class in c++ provided by compiler .

So, if we want to overload C++ constructors in the class, default constructor will not be available and if you want to create an object that call empty constructor, will fail.

For example, in below C++ code example , if we remove empty constructor from the class and create object like “Employee obj”, compiler error will be thrown. As it will not find default constructor. Once, we write Empty constructor in C++ program, it will be fine.

class Employee
{
	int id;	

public:
//Empty Constructor
Employee(){		
	}
	
	//one argument overloaded constructor
	Employee(int id){

		this->id = id;

	}
	
};

Also, if we want to prevent the object creation of the class from outside of the class, we can write the empty constructor and make it private using private access specifier in the C++ program.

For example, in below C++ code , if we try to create the object of the class in main program, compiler will throw an error.

class A{
private:
	A(){}

public:

	//Constructor NOT REQUIRED
	void print(){
	}
};
int main(){
	
	A a;
	a.print();	

	return 0;
}

Related Posts