23

The g++ compiler complains with this error when I declare a friend thusly:

friend MyClass;

instead of

friend class MyClass;

Why should the class keyword be required? (the Borland C++ compiler, BTW, does not require it.)

Couldn't the compiler simply look-up MyClass in the symbol table and tell it was declared as a class? (it is obviously doing the look-up anyway because it complains when MyClass it not declared)

It is not like it is making a forward declaration of the class: I still have to have either declared the class above or at least have forward declared it.

It would make sense to me (would be great actually) if

friend class MyClass;

makes a forward declaration if needed, otherwise it just seems like syntactic salt to me.

I have been merrily using friend statements without the class or struct keyword with no compiler complaints for almost 20 years. Is this something fairly new?

Roger Nelson
  • 1,882
  • 2
  • 15
  • 21

2 Answers2

23

I was surprised about this (and as a result deleted a previous incorrect answer). The C++03 standard says in 11.4:

An elaborated-type-specifier shall be used in a friend declaration for a class.

Then to make sure there's no misunderstanding, it footnotes that with:

The class-key of the elaborated-type-specifier is required.

GCC is the only compiler that I have that complains about the missing class-key, but it looks like other compilers are letting us get away with something non-standard...

Now as for the rationale - you'd have to ask someone who knows more about compilers (or standards) than I do.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
  • 2
    `friend` without class-key works under g++ 4.7.0/4.7.3 with option `-std=c++11` – Interarticle Oct 22 '13 at 18:27
  • It would be better If you update your answer according to C++11 also, C++11 has introduced __extended friend declarations__ . See https://www.ibm.com/developerworks/community/blogs/5894415f-be62-4bc0-81c5-3956e82276f3/entry/introduction_to_the_c_11_feature_extended_friend_declaration3?lang=en – Destructor Aug 17 '16 at 17:57
22

To the point of your question, because it is the way ISO/IEC 14882:2003 specifies it (section 7.1.4). The friend construct is essentially specified as:

friend <declaration>

where <declaration> is the valid declaration of a class, struct, template, or function.

Thus,

MyClass;

is not a valid declaration, whereas:

class MyClass;

or:

struct MyClass;

are.

Idem for, correspondingly:

friend class MyClass;

or

friend struct MyClass;
vladr
  • 65,483
  • 18
  • 129
  • 130