Default parameters with C++ constructors

Rob picture Rob · Oct 9, 2008 · Viewed 234.9k times · Source

Is it good practice to have a class constructor that uses default parameters, or should I use separate overloaded constructors? For example:

// Use this...
class foo  
{
private:
    std::string name_;
    unsigned int age_;
public:
    foo(const std::string& name = "", const unsigned int age = 0) :
        name_(name),
        age_(age)
    {
        ...
    }
};

// Or this?
class foo  
{
private:
    std::string name_;
    unsigned int age_;
public:
    foo() :
    name_(""),
    age_(0)
{
}

foo(const std::string& name, const unsigned int age) :
        name_(name),
        age_(age)
    {
        ...
    }
};

Either version seems to work, e.g.:

foo f1;
foo f2("Name", 30);

Which style do you prefer or recommend and why?

Answer

luke picture luke · Oct 9, 2008

Definitely a matter of style. I prefer constructors with default parameters, so long as the parameters make sense. Classes in the standard use them as well, which speaks in their favor.

One thing to watch out for is if you have defaults for all but one parameter, your class can be implicitly converted from that parameter type. Check out this thread for more info.