Friend functions and classes not permitted to data

I have a situation:
I have a class character
1
2
3
4
5
6
7
8
9
10
11
12
13
14

class Character;
class Village;

class Character
{
    public:
    //Functions
    void charGen(); //Character creation

    friend class Village;
    //Variables
    
};


And a class Village:
1
2
3
4
5
6
     public:
     //Functions
     friend class Character;
     protected:
     //A few variables, including the number of completed quests
     int questsCompleted;


When charGen() is called, a new hero for the user is created. Consequently, questsCompleted must be set to 0;
1
2
3
4
5
6
void Character::charGen()
{
     //Character creation stuff
     
    questsCompleted = 0;
}


According to the Friendship and Inheritance tutorial (http://www.cplusplus.com/doc/tutorial/inheritance/), that code should work, but it doesn't. I am given an error: undefined reference to questsCompleted
Can someone point out what went wrong?

The compiler I am using is Code::Blocks, in case that helps.
Last edited on
Friendship lets you access the private members of a class when you have an object to call them from. If you wanted to keep with that style you would have to pass a Village object into charGen().
Thank you! Are there any other ways to have this class interaction? I have a lot of instances where Character and Village modify each other.
It depends how your game is set up and what other variables you need interacting (there isn't really enough here to say). For example I would expect the questsCompleted to belong to the Character class not the Village.

You could put both objects in your main game class and have them interact from there (or another similar class that accepts both objects to work on them). Class friendship is a risky thing to deal with and I would say avoid it unless you are really sure you need it.

You could make questsCompleted static if it's only ever needed once, but as I said it all depends on what you want to do exactly.
Thanks! I will try these solutions!
Topic archived. No new replies allowed.