7

I want to specify a default value for a friend function, as follows:

friend Matrix rot90 (const Matrix& a, int k = 1);

When compiling this line with Xcode 5.1.1, I get the following error

./Matrix.hh:156:19: error: friend declaration specifying a default argument must be a definition

What is the proper way of fixing it?

Thanks!

Anastasia
  • 73
  • 1
  • 5
  • 2
    The error says i all, you have to define the function, not just declare – Rakib Apr 28 '14 at 06:29
  • 2
    @BЈовић Thanks. Second try. Or use two functions, `friend Matrix rot90 (const Matrix&);` and `friend Matrix rot90 (const Matrix&, int);`. – juanchopanza Apr 28 '14 at 06:42
  • Update: as Rakibul Hasan suggested, defining the function instead of just declaring it solves the problem. – Anastasia Apr 28 '14 at 09:00
  • possible duplicate of [Friend declaration specifying a default argument must be a definition](http://stackoverflow.com/questions/22533511/friend-declaration-specifying-a-default-argument-must-be-a-definition) – Rich Apr 14 '15 at 10:33

1 Answers1

11

The standard says (§8.3.6):

If a friend declaration specifies a default argument expression, that declaration shall be a definition and shall be the only declaration of the function or function template in the translation unit.

That is, if you specify the default argument on the friend declaration, you must also define the function right then and there. If you don't want to do that, remove the default argument there and add a separate declaration for the function that specifies the default arguments.

// forward declarations:
class Matrix;
Matrix rot90 (const Matrix& a, int k = 1);

class Matrix {
    friend Matrix rot90 (const Matrix&, int); //no default values here
};
ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
  • Thanks, this solves it and is more elegant than adding the definition. Additional question: the class is defined in a header file. Should the forward declaration appear in this header file as well? – Anastasia Apr 28 '14 at 10:07
  • @Anastasia It does not have to be the same header file, it could also be another header file that is pulled in by your class header. But in the end, once all the includes have been resolved, you should end up with the order above, where every `.cpp` file first sees the free-standing declaration and then the friend declaration. – ComicSansMS Apr 28 '14 at 10:17