Hey all,
It's been a while since I found a problem in C++ that I couldn't solve on my own, but I'm working on a sort of "interactive fiction" program for class.
There is a parent class called GameObject, and pretty much everything except for the Player class is a child of this parent class. One of these child classes is the Location class, which has a member function "AddExit" for the main program to add an exit (to another location).
I created an object with:
GameObject* foo = new Location("name", "description");
then later tried to call:
foo->AddExit(&bar);
which the compiler obviously doesn't like. I think I know why it's not working, but do you have any tips to fix it? Thanks in advance.
It's not any old GameObject that has AddExit, it's only a Location that can do that.
So you either need make foo a Location*, or check at runtime that the object is a Location* (with dynamic_cast). My guess is that foo should be a Location*. Casting, in general, isn't something to be used lightly.
I'd love to make foo a Location*, but the problem is that the pointer needs to be able to refer to not only Location*, but other children of GameObject like portable objects and so forth.
I tried using:
dynamic_cast<Location*>(foo)->AddExit(&bar);
but I get an "invalid conversion" error.
EDIT:
Neither
static_cast<Location*>(foo)->AddExit(&bar):
nor
((location*)foo)->AddExit(&bar);
work.
EDIT2:
Evidently the problem was in my call of AddExit. I had completely forgotten to convert the parameter! Thanks for your help.
If you know that foo is always a Location*, then you can use static_cast rather than testing it with dynamic_cast. It's a bit faster and corresponds to your knowledge that foo is a Location*.