简体   繁体   中英

Friend function cannot access private member variable

I'm having two classes, PlayerCharacter and Ability . The Ability class has an pure virtual function which I declare as a friend to PlayerCharacter . However, I seem to be unable to access the private members within the friend declared function. Is it something I overlook?

I have attemped to declare the child function rather than the virtual one as the friend function, but to no effect.

player_chracter.h :

#include "ability.h"

class PlayerCharacter : public Character {
private:
    // Friend function
    friend bool Ability::ExecuteAbility(PlayerCharacter& in_player);

    // This doesn't work either
    //friend bool Dash::ExecuteAbility(PlayerCharacter& in_player);

    // Private variable
    float top_speed_;
}

ability.h :

//Forward declaration
class PlayerCharacter;

class Ability {
public:
    Ability();
    ~Ability();
    virtual bool ExecuteAbility(PlayerCharacter& in_player) = 0;
};
//---------------------------------------------------------
class Dash : public Ability {
public:
    Dash();
    ~Dash();
    bool ExecuteAbility(PlayerCharacter& in_player);
};

ability.cpp :

#include "ability.h"
#include "player_character.h"   //Follow through on forward declaraction

bool Dash::ExecuteAbility(PlayerCharacter& in_player) {
    float example = in_player.top_speed_;
}

In the code above, why cannot I access top_speed_ and put it in the float example variable?

As per [class.friend]/10 , friendship is not inherited. A derived class does not automatically become a friend of a class just because its parent class is a friend of that class.

The reason why the below also does not work either is probably because Dash is not defined before the function ExecuteAbility is defined.

friend bool Dash::ExecuteAbility(PlayerCharacter& in_player);

However, with the proper order of definitions it will work. See DEMO .

From cppreference :

Friendship is not transitive (a friend of your friend is not your friend)

Friendship is not inherited (your friend's children are not your friends)

Even if Dash::ExecuteAbility overrides a friend function from its base class, it does not benefit from it. You'll have to rethink your design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM