Consider the following code where I'm trying to introduce a default constructor as well as a parameterized one for class A. This way was introduced in recent c++ improvements.
class A {
private:
unsigned int count;
public:
A(int new_c) : count(new_c) {}
A() : A(10) {}
};
vs the old way of setting a default parameter on parameterized constructor and ignoring the default constructor completely.
class A {
private:
unsigned int count;
public:
A(int new_c = 5) : count(new_c) {}
};
Is there any advantage using 1st method over the 2nd one apart from following modern conventions?
Functionally there is no difference. Know that there is even another option available with non-static member initialization (since C++11):
class A {
private:
unsigned int count = 10;
public:
A() = default;
A(int new_c) : count(new_c) {}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With