Can we have default arguments in constructor in C++?

Answer: Yes, we can have default arguments in constructor in C++. Below class “MLogger “ example contains default argument in constructor i.e. MLogger(bool isON = false).

This is the pseudo code for logging errors, that logs errors if object has been created with “true” value i.e. MLogger LogOn(true);, so, constructor will accept the value true and set it to member variable “isLoggerEnable”. On the basis of this condition function logError() will log errors.

If we create object without passing true value(MLogger LogOff;), constructor will use default value “false” set to isLoggerEnable member variable and function logError will not log errors.

class MLogger
{
	bool isLoggerEnable;
public:
	//Default argument in constructor
	MLogger(bool isON = false):isLoggerEnable(isON)
	{
		cout<<" Logger Status :"<<isLoggerEnable<<"\n";
	}

	void logError(){
		if(isLoggerEnable){
			cout<<" Error logged..."<<"\n";
		}else{
			cout<<" Logging not required..."<<"\n";
		}
	}
};
//----------TEST Default Arguments Constructor----
int main()
{
	// This object will not be able to Log errors
	MLogger LogOff;
	LogOff.logError();

	//This object can log errors.
	MLogger LogOn(true);
	LogOn.logError();
	

	return 0;
}

Output:

Logger Status :0
Logging not required…
Logger Status :1
Error logged…

Related Posts