0

I was going through this post Default parameters with C++ constructors and I had a question regarding the placement of optional arguments in a constructor. For example:

Class TestCode {
private:
      int _length;
      int _width;
      int _height;
public:
     TestCode(int length = 5, int width, int height=3):
             _length(length), _width(width),_height(height){

} } ;

// Using the class

  TestCode testRectangle(2);
  TestCode testRectangle2(2,3);

Is the testRectangle object constructed with width 2 and default length and height? What happens in the case of testRectangle2? Are the parameters assigned correctly. Given this ambiguity, should be just have all option parameters at the end of the constructor?

Community
  • 1
  • 1
vkaul11
  • 4,098
  • 12
  • 47
  • 79

3 Answers3

4

Yes, you must have all optional parameters at the end of the declaration. Your example:

TestCode(int length = 5, int width, int height=3)

won't compile.

champagniac
  • 444
  • 3
  • 4
2

In fact, you must have all default parameters come after all other non-default parameters in C++.

John Dibling
  • 99,718
  • 31
  • 186
  • 324
1

Does your code even compile if you put them at the start? Afaik it shouldn't.

Yes, it is best practice to put them at the end, after non-optional parameters. It is also a good idea to put them in sorted order of how often they are used if there is no compelling reason not to.

Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79
  • Actually it was compiling without the TestCode testRectangle2(2,3) code but giving error otherwise. There was a warning, so I was confused. – vkaul11 May 30 '13 at 19:11