2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[C++11] friend

Posted at

friend is a keyword that will ignore the property (private, protected, public) of class members. That is to say your friend class could access any of your members no matter it is private or public.

The definition of friend has nothing changed in C++11 but more convenient.

As you can see here, we do not need to specify the class keyword anymore.

class Enemy {
private:
    float hp;
    float attack_damage;

    // C++98 OK
    // C++11 OK
    friend class Admin;

    // C++98 error: C++ requires a type specifier for all declarations
    // C++11 OK
    friend Admin;
};

This change enables us to use the friend keyword to template.

template<typename T> class Enemy {
private:
    float hp;
    float attack_damage;

    friend T;
};

When T is int, nothing will happen.

With this we can specify which class can access the private member of this class when we create a class instance.

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?