Search code examples
c++thisfriend

C++ : friends of class and "this" pointer


I have one little question for you :), I understand that every method "secretly" gets "this" pointer of some class that they are inside but why that wont happen to "friend" functions ? Is it because they are NOT methods of class?

Can anyone explain whole machinery, i am very interested in how "this" really works!

thanks in advance! :)


Solution

    • friend functions and classes are just used for access control checked by the compiler.
    • friend functions are just standard functions, so there won't be any differences regarding calling conventions.
    • friend functions are not member of any class, so no this pointer is passed (as done with static member functions)

    Non-static member function of a class will get a hidden this pointer (depending on the ABI this is often the first argument), static member functions don't get the this pointer because they don't act on instance data.

    How exactly the this pointer is passed to a member function heavily depends on the used ABI, which depends on the architecture and operating system. Either it will be pushed on the stack, or it will be passed through a well known register.

    Please consider reading "Where is the 'this' pointer stored in computer memory?".