C++ – Correct Way to Define Default Argument for Friend Function

c++c++11xcode5

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!

Best Answer

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
};
Related Question