By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,604 Members | 1,490 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,604 IT Pros & Developers. It's quick & easy.

Scoping Problems

P: 2
Hello everyone,

I'm a novice programmer and am having trouble with a text-adventure game I am programming. There are two classes, Hero and Monster, that contain functions that I want to be able to pass pointers to objects of the opposite class into, but the compiler complains that it cannot recognize the identifiers. I have included both "Hero.h" and "Monster.h" in each cpp file, and I get different compiler errors depending on the order I include the files, so I'm assuming it's a scoping issue. I can't figure out how to resolve it though. If anyone could give me some suggestions I would appreciate it. I've included some of the code to help clarify.

class Hero
{
public:
Hero();
void nameHero(string n);
void attack(Monster *monster);
...
}


class Monster
{
public:
Monster();
void nameMonster(string n);
void attack(Hero *hero);
...
}


I keep getting errors in the declaration of the 'attack' fuction for each class.
Nov 16 '06 #1
Share this Question
Share on Google+
4 Replies


sivadhas2006
100+
P: 142
Hi,

do the forward declarations for the class.
It may solve your problem.

Expand|Select|Wrap|Line Numbers
  1.    class Monster;
  2.    class Hero
  3.    {
  4.       public:
  5.          Hero();
  6.          void nameHero(string n);
  7.          void attack(Monster *monster);
  8.       ...
  9.    }
  10.  
Regards,
M.Sivadhas.
Nov 16 '06 #2

vpawizard
P: 66
Another cleaner (but bit expensive) solution is use of virtual functions. Define attack() virtual in base class and inherit in Hero and Monster classes. Define functionality in these classes n in the calling function(assuming main()), point to appropriate object.
Nov 16 '06 #3

P: 2
Thanks for the advice guys. I decided to take the easy way out with the forward declarations and it compiled right away.
Nov 16 '06 #4

sivadhas2006
100+
P: 142
Thanks for the advice guys. I decided to take the easy way out with the forward declarations and it compiled right away.
ok.

Regards,
M.Sivadhas.
Nov 17 '06 #5

Post your reply

Sign in to post your reply or Sign up for a free account.