C++ constructor default value header file

10,392

Solution 1

Don't provide the default value in the definition:

foo::foo(bool debug) {
    dbg = debug;
}

Now its correct. Default value should be provided in the declaration only, which you've done in the header file.

By the way, prefer using member-initialization-list over assignments:


And of course, if its declaration-cum-definition, then you've to provide the default value (if you want it) right in the declaration-cum-definition:

class foo {
    bool dbg;
    public:
        foo(bool debug = false) : dbg(debug) {}
                               //^^^^^^^^^^^ using member initialization list
}

Solution 2

The default value must be only in the declaration of the function, when the declaration and the definition are separated.


You could add the default value as an comment, if you like, but you should be aware, because changing the default value and forgetting to change the comment could cause some misleading (:

For example:

foo(bool debug = false);

//...

foo::foo(bool debug /* = false */ )
{ /* ... */ }

Solution 3

In C++(I dont know of other languages), the default arguments are a part of only function declaration & not function definition.

class foo {
    bool dbg;
    public:
        foo(bool debug = false);
}

is fine, change your defintion to:

foo::foo(bool debug) {
    dbg = debug;
}

Solution 4

It doesn't need a default argument in member function definition,

foo::foo(bool debug) {
    dbg = debug;
}
Share:
10,392

Related videos on Youtube

Clivest
Author by

Clivest

Updated on June 04, 2022

Comments

  • Clivest
    Clivest almost 2 years

    I'm trying to create a constructor with a default value. The complication comes from the use of separate header and code files for the class. I've got a header file that contains:

    class foo {
        bool dbg;
        public:
            foo(bool debug = false);
    }
    

    And a code file containing:

    foo::foo(bool debug = false) {
        dbg = debug;
    }
    

    When I try and compile with g++ (i.e. g++ -c foo.cc), it gives an error:

    foo.cc:373:65: error: default argument given for parameter 1 of ‘foo::foo(bool)’
    foo.h:66:4: error: after previous specification in ‘foo::foo(bool)’
    

    What am I doing wrong?