Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object construction : default parameter vs delegation

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?

like image 514
Abhinav Gauniyal Avatar asked Sep 02 '26 04:09

Abhinav Gauniyal


1 Answers

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) {}
};
like image 70
Cory Kramer Avatar answered Sep 03 '26 19:09

Cory Kramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!