0

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?

Geeky Quentin
  • 2,469
  • 2
  • 7
  • 28
  • 2
    [ADL](https://en.cppreference.com/w/cpp/language/adl). You should post the non working code together with the compiler error, rather than code that does not have the error, read about [mcve] – 463035818_is_not_an_ai Aug 01 '23 at 10:46
  • 1
    `String s = strdup("What");` That's a memory leak. What happens with the memory that `strdup` allocates? Also note that `strdup` is not a standard C++ function. And in C++ you should almost never use C-style null-terminated strings yourself. – Some programmer dude Aug 01 '23 at 10:48
  • 1
    Also please read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Some programmer dude Aug 01 '23 at 10:49

0 Answers0