views:

580

answers:

4

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?

+1  A: 

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
+1  A: 

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

Fred Larson
+12  A: 

.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
Thanks, appreciate the quick response!
royvandewater
+1  A: 

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
and change it in two places if needed? ;-)
Michael Krelin - hacker
99% of times, its not going to change. So you are talking about a rare use case :-)
Naveen
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
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.
@Michael: Extra checks from the compiler just to help make code easier to follow? That is sooo un-C. :-)
T.E.D.