Search code examples
c++friendpure-virtual

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?


Solution

  • 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.