Static and friend function in a class

Use of static and friend function in a class

Questions by jithinkm

Showing Answers 1 - 9 of 9 Answers

matsp

  • Nov 20th, 2008
 

The keyword static indicates that the function is part of the class, but does not take the object as the hidden "this" parameter. This is useful for example when you need a custom creation step of the class object [beyond what you can do in the constructor], or for singleton classes.

Static can also be used for variables, in which case it's a class-variable that is the only instance for all classes.

The keyword friend is used within a class to indicate that a class can access private member functions and private member variables even though the function is not part of the class itself. This allows the class to determine that certain functions are "friendly" or "trusted" and can be used to "look inside" the class.

--
Mats

  Was this answer useful?  Yes

ajrobb

  • Sep 22nd, 2010
 

A static function is associated with the class and not an object. It has access to other static functions and variables in the class and it is a friend.

A friend function is declared in a class but does not belong to the class. It can access private members and methods of object parameters passed to it.

#include <iostream>

class A {
private:
  int a;
public:
  A(int val) : a(val) {}
  friend std::ostream & operator<<(std::ostream &, A const &);
};

inline std::ostream & operator<<(std::ostream & out, A const & a) {
  return out << a.a;
}

int main() {
  A a(2);
  std::cout << a << 'n';
}

  Was this answer useful?  Yes

Navnit kumar

  • Sep 16th, 2014
 

What is difference between friend function and static function?

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions