0

the title might seem a little bit confusing but I'll try to explain that. I've got a class CGameMode:

#pragma once

#include <string>
#include <iostream>
#include "../Hero/Hero.h"
#include "../Weapon/Weapon.h"
#include "../Armor/Armor.h"

class CGameMode
{
private:
    CHero Hero;
    CWeapon Weapon;
    CArmor Armor;

    std::string FileName = "save.txt";
protected:

public:
    void InitializeGame();
    void CreateGame();
    void LoadGame();
    void SaveGame();
    CGameMode* GetGameMode() { return this; }
};

As you can see, the class contains objects of classes: CHero, CWeapon and CArmor. Let's take a look on one of these classes:

#pragma once

#include "../Enemy/Enemy.h"
#include "../GameMode/GameMode.h"

class CHero : public CEnemy
{
private:
    int Energy = 0;
    int ExperiencePoints = 0;
    int Level = 0;

    friend class CGameMode;
protected:

public:
    CHero();
    CHero(std::string Name, int Health, int Energy, int ExperiencePoints, int Level);
};

The most important is this line of code:

friend class CGameMode;

(CArmor and CWeapon also friend the CGameMode class).

The problem is the program does not compile. But if I remove Hero, Weapon and Armor members from CGameMode class, the program compiles and everything works just fine.

So the question is: How can I make the CGameMode class friended with CWeapon, CArmor and CHero and in the same time, the objects of these classes can be contained by CGameMode?

Vatnax
  • 11
  • 1
  • "*The problem is the program does not compile.*" What is the full compiler error you receive? – scohe001 Nov 09 '20 at 14:12
  • Do you really need to be friends with everything? Friends should be used sparingly, if other classes need access to private members then the members should either be public or have accessor methods – Alan Birtles Nov 09 '20 at 14:14
  • 2
    As to your problem I suspect it is due to circular includes rather than friends (difficult to tell without a [mre] and the error message), see https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes – Alan Birtles Nov 09 '20 at 14:17
  • After adding the missing bits the code you've given compiles without error: https://godbolt.org/z/aK9svT – Alan Birtles Nov 09 '20 at 14:19
  • You're approaching this from the wrong end. Design your class interfaces so friendship is unnecessary. – molbdnilo Nov 09 '20 at 14:21
  • I never use `frind` keyword and IMO nobody should. Friendships creates code entanglement so it should be avoided. – Marek R Nov 09 '20 at 16:07

0 Answers0