C++ classes, methods

Posted by Zeno on Fri 29 Sep 2006 01:24 AM — 7 posts, 16,271 views.

USA #0
Okay, I have two classes. One is a list of warriors and another is an arena (3D array of rooms [bool]).

In the list class, I have a method that "battles" and warriors can be killed in this method. When a warrior is killed, the room they're in (in the arena) should be made true (bool). But apparently you're not allowed access to other classes in C++. I get the error:

'ArenaClass::CloseRoom' : illegal call of non-static member function


What can I do here to accomplish this? I cannot use inheritance yet on this assg.

Australia Forum Administrator #1
You need to call an instance of the class, not the class itself.

Instead of:

ArenaClass::CloseRoom ()

You need something like this:

ArenaClass myarena;

myarena.CloseRoom ();
USA #2
Well I did that in the client, but not implementation (with the methods).

So I should just pass that into the Battle method? I think I know what to do now.

Hmm doesn't seem to work. This is the method header:
void WarListClass::Battle( ArenaClass arena)


Getting error:
syntax error : identifier 'ArenaClass'
Amended on Fri 29 Sep 2006 01:53 AM by Zeno
USA #3
Classes like all types need to have been declared (but not necessarily defined) before you can use them. Usually it's enough to include the header files. However you can get into nasty circular dependencies if each class needs to refer to the other in the headers; in that case you should use forward declarations.
USA #4
Not sure I follow. Both these classes are in the same .h file and the methods in the same .cpp file.
USA #5
Well, the compiler has to have seen the class 'Foo' before you use it in a method declaration. For example:


[.h file]
class Bar
{
  void doSomething(Foo f);
}

class Foo
{
  void bla();
}

This is invalid code because 'Foo' has not seen 'Bar' yet. Now consider this:


[.h file]
class Bar
{
  void doSomething(Foo f);
}

class Foo
{
  void doSomethingElse(Bar b);
}

In this case Foo will be happy but we still have the problem of Bar not seeing Foo and therefore the method signature is invalid. Here is the solution:


[.h file]

// Forward declarations:
class Bar;
class Foo;

// Full declarations:

class Bar
{
  void doSomething(Foo f);
}

class Foo
{
  void doSomethingElse(Bar b);
}


Here, we forward-declare the two classes, so that everything is happy -- when the compiler goes through the real declarations, it has already been told that there is such a class as 'Foo' and 'Bar', so everything will work.

Does this make more sense? Inter-dependencies of classes can get really tricky, especially when you have circular dependencies.
USA #6
Yeah I figured that out last night and went to bed. Thanks though. :P