Consider the code below:
#include <bits/stdc++.h>
class String {
char* data;
int len;
public:
String(char* str) : data(strdup(str)), len(strlen(data)) { }
friend void display(String& str) {
std::cout << str.data << std::endl;
}
};
int main() {
String s = strdup("What");
display(s);
return 0;
}
The function display(String&)
is a friend of the class String
and is implemented inside the class itself.
The output is:
What
When I remove the arguments of the function display()
, and call this function without any arguments, I get a compilation error:
error: ‘display’ was not declared in this scope
I don't understand the behaviour of a friend function implemented inside the class itself. From my knowledge, as the function is not in the global scope, it shouldn't be accessible. But when the argument passed is of the type String
, the code runs perfectly and prints the desired result.
What's a plausible explanation for this kind of behaviour?