4

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! :)

user2866794
  • 41
  • 1
  • 4
  • 3
    That's right. `friend` functions are non-member functions, so they don't know anything about `this`. They are just granted access to the non-public members of the class. – juanchopanza Oct 10 '13 at 11:43
  • 1
    http://stackoverflow.com/questions/16585562/where-is-the-this-pointer-stored-in-computer-memory – Spook Oct 10 '13 at 11:53
  • Consider a common friend function, `Foo operator+(Foo const& a, Foo const& b)` - to which `Foo` should `this` point? Now consider `Foo operator+(Bar const& a, Foo const& b)`, friend of both. Can you even say what the type of `this` is? – MSalters Oct 10 '13 at 11:56

2 Answers2

2
  • 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?".

Community
  • 1
  • 1
villekulla
  • 1,039
  • 5
  • 15
  • 1
    Be careful. C++ standard does not say, that *this* should be passed as first hidden argument (though *usually* it is done this way) – Spook Oct 10 '13 at 11:55
2

"Friendship" and "Membership" are two different things. A function can be a member function or not, and independantly be a friend function or not.

You can declare a member function to be a friend function of another class, i.e.

class B{

   friend void A::func(B);
   //stuff
};

Here, the member function func from class A is declared as friend and can access B's private, and it will have a this pointer, that points to the object of class A on which func has been called.

The this pointer is an implicit parameter of non-static member functions, which is described in section 9.3.2 of the C++ Standard. How it is passed to the function depends on your compiler/architecture, i.e. it is implementation defined (so you might want to read your favorite compiler's documentation to learn about how it manages this pointers).

JBL
  • 12,588
  • 4
  • 53
  • 84