Scoping Problems

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bob357
    New Member
    • Nov 2006
    • 2

    Scoping Problems

    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(str ing n);
    void attack(Hero *hero);
    ...
    }


    I keep getting errors in the declaration of the 'attack' fuction for each class.
  • sivadhas2006
    New Member
    • Nov 2006
    • 142

    #2
    Hi,

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

    Code:
       class Monster;
       class Hero
       {
          public:
             Hero();
             void nameHero(string n);
             void attack(Monster *monster);
          ...
       }
    Regards,
    M.Sivadhas.

    Comment

    • vpawizard
      New Member
      • Nov 2006
      • 66

      #3
      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(assumi ng main()), point to appropriate object.

      Comment

      • bob357
        New Member
        • Nov 2006
        • 2

        #4
        Thanks for the advice guys. I decided to take the easy way out with the forward declarations and it compiled right away.

        Comment

        • sivadhas2006
          New Member
          • Nov 2006
          • 142

          #5
          Originally posted by bob357
          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.

          Comment

          Working...