29

I have a cpp file like this:

#include Foo.h;
Foo::Foo(int a, int b=0)
{
    this->x = a;
    this->y = b;
}

How do I refer to this in Foo.h?

royvandewater
  • 1,368
  • 2
  • 14
  • 16

4 Answers4

60

.h:

class Foo {
    int x, y;
    Foo(int a, int b=0);
};

.cc:

#include "foo.h"

Foo::Foo(int a,int b)
    : x(a), y(b) { }

You only add defaults to declaration, not implementation.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
11

The header file should have the default parameters, the cpp should not.

test.h:

class Test
{
public:
    Test(int a, int b = 0);
    int m_a, m_b;
}

test.cpp:

Test::Test(int a, int b)
  : m_a(a), m_b(b)
{

}

main.cpp:

#include "test.h"

int main(int argc, char**argv)
{
  Test t1(3, 0);
  Test t2(3);
  //....t1 and t2 are the same....

  return 0;
}
Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
8

The default parameter needs to be written in header file.

Foo(int a, int b = 0);

In the cpp, while defining the method you can not specify the default parameter. However, I keep the default value in the commented code so as it is easy to remember.

Foo::Foo(int a, int b /* = 0 */)
Naveen
  • 74,600
  • 47
  • 176
  • 233
  • 2
    and change it in two places if needed? ;-) – Michael Krelin - hacker Sep 17 '09 at 17:36
  • 1
    99% of times, its not going to change. So you are talking about a rare use case :-) – Naveen Sep 17 '09 at 17:40
  • 1
    In my opinion it's too bad the C++ standard doesn't *require* that it be in both places and check that it's the same. Defaults for parameters are as much a part of the interface as parameter types. The compiler should check it. – Michael Burr Sep 17 '09 at 17:46
  • 1
    The problem with doing that is that the default can change in the header, and the compiler will not inform you that the cpp needs changing there too. Code in comments cannot be trusted. – T.E.D. Sep 17 '09 at 17:48
  • 2
    @Michael: Extra checks from the compiler just to help make code easier to follow? That is sooo un-C. :-) – T.E.D. Sep 17 '09 at 17:50
5

You need to put the default arguments in the header, not in the .cpp file.

Fred Larson
  • 60,987
  • 18
  • 112
  • 174