# quick question about classes (c++)

## Recommended Posts

I was wondering if there is anyway to declare a class before you fully code it, kind of like what you can do for a function example: void whatever (); I'm making a text rpg and I have two main classes character and enemy, they each have a function called attack but I get an error saying Identifier 'Character' etc, because the character class hasn't been created yet, but I do the samething for the character class and it has no problem because I made the enemy class first as you can see:

class enemy
{
public:
string name;
int hp;
int hpLeft;
int mp;
int mpLeft;
int str;
int wis;
int dex;
int spe;
int expGivin;
int moneyGivin;
int Attack(character);

};

class character
{
public:
int level;
int exp;
int hp;
int hpLeft;
int mp;
int mpLeft;
int str;
int wis;
int dex;
int spe;
int money;
int Attack (enemy);

};


can you make a class prototype or is there another way to do this?

##### Share on other sites
Yes, its as simple as sticking class character; above enemy. Its called a 'forward declaration' because you declare the class's existance ahead of its body declaration.

Note however that you will be unable to 'use' the forward declared class until it has been fully declared.

##### Share on other sites
Yes, you can forward declare a class. To do so just type "class ClassName;". However there are limitations. With functions all you need is a signature, and you can do what you will with it. With a class or structure you obviously cannot access member functions or variables before the class is defined. Likewise you cannot access the size using sizeof(). This has implications for inline functions.

I can't remember if you can declare a function taking an incomplete type by value, but if you can you won't be able to call it until it is defined I imagine. But 99% of functions take const references instead of an object by value. If your Attack functions take const references then a forward declaration should do just fine.

##### Share on other sites
Quote:
 Original post by rip-offI can't remember if you can declare a function taking an incomplete type by value, but if you can you won't be able to call it until it is defined I imagine.

I think you should be able to take the incomplete type by-value. It's really only the method's prototype that's in the class, so long as the methods body is declared after the full definition of the character class then it should be ok I reckon.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
627702
• Total Posts
2978712

• 21
• 14
• 12
• 10
• 12