0

Maybe the title doesn't fit enought.

I have two classes "Player" and "Upgrade"

  • Player is declared before Upgrade.

But I need a method in the Player class that uses a pointer to the Upgrade class

If I try to compile it I get ‘Upgrade’ has not been declared. I give a sample code. Notice i can't just switch the location of both class because Upgrade has also some methods that has Pointers to Player

class Player{
    string Name;
    getUpgrade(Upgrade *); // It's a prototype
};
class Upgrade{
    double Upgradeusec;
    somePlayerData(Player *); // It's a prototype
};

PD: I have been searching for this for like 1 hour, without results.

Notice: This is just a sample code, because the real one goes large

  • Please delete it. It has no solution. C++ language doesn't allow nested class forward declare. I get it, better use reference to "parent" class insteat of a nested class – Kevin Guanche Darias Aug 21 '13 at 04:34

4 Answers4

3

You need to forward declare Upgrade ahead of the definition of the Player class; e.g.

class Upgrade;
class Player { ... };
class Upgrade { ... };

This of course implies a very tight coupling between the two classes that might be undesirable depending on the situation.

sfjac
  • 7,119
  • 5
  • 45
  • 69
  • Ok, it would work. But i'm trying to access an inner class. Upgrade::Requisites . I get ‘Requisites’ in ‘struct Upgrade’ does not name a type. +1, because gives me usefull information about "forward declare" – Kevin Guanche Darias Aug 21 '13 at 04:13
  • Ah. I don't think that's allowed in C++. See http://stackoverflow.com/questions/1021793/how-do-i-forward-declare-an-inner-class – sfjac Aug 21 '13 at 04:35
2

You can forward declare it.

In the file having the code for the class Player simply add the below line at the top after all the #includes and #defines

class Upgrade;

class Player
{
      //the definition of the Player class
}

The compiler will honor this forward declaration and will go ahead without complaining.

Prahalad Deshpande
  • 4,709
  • 1
  • 20
  • 22
1

What is forward declaration in c++?

Just add a forward declaration in your code:

class Upgrade; //forward declaration
class Player{
    string Name;
    getUpgrade(Upgrade *); // It's a prototype
};
class Upgrade{
    double Upgradeusec;
    somePlayerData(Player *); // It's a prototype
}

;

Community
  • 1
  • 1
iampranabroy
  • 1,716
  • 1
  • 15
  • 11
0

You need forward declaration. http://en.wikipedia.org/wiki/Forward_declaration C++ have a lot of complex rule to specific when incomplete type can be used.

class Upgrade;   //<<<< add this line.
Class Player{
    string Name;
    getUpgrade(Upgrade); // It's a prototype
};
Class Upgrade{
    double Upgradeusec;
    somePlayerData(Player); // It's a prototype
};
ZijingWu
  • 3,350
  • 3
  • 25
  • 40