Reputation: 149
Why friend class need not forward declaration but member function need?
friend class:
class String0{
friend class String;
private:
int size = 0;
string s;
};
class String {
public:
string combine(const string &s1);
private:
int size = 0;
string s;
};
member friend:
class String {
public:
string combine(const string &s1); //why need this?
private:
int size = 0;
string s;
};
class String0 {
friend string String::combine(const string &);
};
String String::combine(const string &s1){...}
Classes and nonmember functions need not have been declared before they are used in a friend declaration. But why member function need?
Upvotes: 2
Views: 119
Reputation: 36401
Standard gives an example:
13.3 Friends [class.friend] 3/
class C; typedef C Ct; class X1 { friend C; // OK: class C is a friend }; class X2 { friend Ct; // OK: class C is a friend friend D; // error: no type-name D in scope friend class D; // OK: elaborated-type-specifier declares new class };
friend class D
both forward declares class D
and a friend relationship with it.
Upvotes: 1
Reputation: 10425
A friend class/function declaration IS a declaration in itself and forward-declares the class/function. You got that right.
Now if you could forward declare a member function of class A
as a friend
in class B
, that means you are changing the interface of class A
.
Imagine I did
class foo {
public:
friend void std::vector<int>::fun();
};
Am I adding a function to std::vector<int>
?
Upvotes: 2