3
// Case A
class Point {
private:
    int x;
    int y;
public:
    Point(int i = 0, int j = 0);  // Constructor
};

Point::Point(int i, int j)  {
    x = i;
    y = j;
    cout << "Constructor called";
}

// Case B:
class Point {
private:
    int x;
    int y;
public:
    Point(int i, int j);  // Constructor
};

Point::Point(int i = 0, int j = 0)  {
    x = i;
    y = j;
    cout << "Constructor called";
}

Question> Both Case A and Case B compile without problems with VS2010.

Original I assume only Case A works because I remember that the default parameters should be introduced in the place where the function is declared rather than the location of its definition. Can someone correct me on this?

Thank you

q0987
  • 34,938
  • 69
  • 242
  • 387
  • See this: http://stackoverflow.com/q/4989483/811335 – A. K. Aug 20 '13 at 18:40
  • 1
    This is a duplicate of a question from a few days ago where it turned out the C++ standard has a defect making this code technically legal but an undue burden on the implementation. I'll see if I can find it. – Mark B Aug 20 '13 at 18:41
  • possible duplicate of [default argument, gcc vs clang](http://stackoverflow.com/questions/18313509/default-argument-gcc-vs-clang) – Mark B Aug 20 '13 at 18:43

1 Answers1

0

If you put the default parameters into the method definition, then only those who see the definition would be able to use the default parameters. The only problem would be if you tried something like this:

public:
    Point(int i = 0, int j = 0);

(...)

Point::Point(int i = 0, int j = 0) { ... }

Then you would get a build-time error.

// EDIT: But I'm curious what Mark B. will find as mentioned in a comment under your question.

// EDIT2: And also apparently clang compiler doesn't like Case B.

Filip Vondrášek
  • 1,208
  • 1
  • 13
  • 26
  • One of the objectives of default parameters is to document what the defaults are. As such, placing it in the header (declaration) is far more useful than placing it in the implementation (which may not be seen if a static library was created, for example). The standard allows for both, but I would strongly discourage placing it in the implementation. – Zac Howland Aug 20 '13 at 18:47
  • 1
    Yeah, I mean - it is possible to do it, but you'd be silly if you have actually done it. – Filip Vondrášek Aug 20 '13 at 18:48