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

(Last Updated On: March 17, 2018)

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.

 

Output:

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