Is it possible to have 1 constructor have the option of being a default constructor if a parameter is not passed in.
Example, instead of having 2 constructors, where 1 is the default constructor and another is a constructor that initializes numbers passed in, is it possible to only have 1 constructor that if a value is passed in, set that value to a member function, and if no value is passed in, set the member function to a number.
example:
WEIGHT.H file:
class Weight
{
public:
Weight() { size = 0; }
Weight(int a) : size(a) {}
int size;
};
MAIN.CPP file:
int main(void)
{
Weight w1;
Weight w2(100);
}
I’ve been working on different school projects and they all require to have different types of constructors, and i’m wondering if there is a way to only have it once so it saves time.
Thanks for the help.
Yes, a constructor parameter may have a default argument, just like other functions can. If all of the parameters of a constructor have default arguments, the constructor is also a default constructor. So, for example,
This constructor may be called with a single argument or with no arguments; if it is called with no arguments,
0is used as the argument for theaparameter.Note that I’ve also declared this constructor
explicit. If you have a constructor that may be called with a single argument, you should always declare itexplicitto prevent unwanted implicit conversions from occurring unless you really want the constructor to be a converting constructor.(If you aren’t familiar yet with converting constructors or implicit conversions, that’s okay; just following this rule is sufficient for most of the code you’ll ever write.)