I am making a program where there is a Hero who has a Sword. I have a class for both of those. In the header I get the error: expected ')' before '*' token
on the line Sword(Hero* h);
in the header of Sword. Here is the compete file (Sword.h):
#ifndef SWORD_H
#define SWORD_H
#include <Hero.h>
class Sword {
public:
Sword(Hero* h);
virtual ~Sword();
};
#endif // SWORD_H
Hero.h is in the same directory as Hero.h, and I'm using Code::Blocks.
I've looked through other posts and couldn't find anything that helped, so any given would be appreciated.
EDIT: Here is the content of Hero.h:
#ifndef HERO_H
#define HERO_H
#include <string>
#include <SDL.h>
#include <SDL_image.h>
#include <stdio.h>
#include <Sword.h>
#include <Sprite.h>
#include <Window.h>
class Hero : public Sprite {
public:
Hero(Window* w);
void update();
void event(SDL_Event e);
~Hero();
protected:
private:
bool up;
bool right;
bool left;
bool down;
Window* window;
Sword* sword;
};
#endif // HERO_H
You cannot include Sword.h from Hero.h and Hero.h from Sword.h, the inclusion chain has to stop somewhere. You can use a forward declaration to fix it:
//#include <Hero.h> // remove this
class Hero; // forward declaration
class Sword {
public:
Sword(Hero* h);
virtual ~Sword();
};
This works because you don't need the definition of Hero
in Sword.h. The compiler only needs to know that Hero
is a class
.
You can do the same in Hero.h: replace #include <Sword.h>
with class Sword;
. You can then include the files in the corresponding .cpp files where you need the definitions in order to use the classes.
Rule of thumb: always use forward declaration, unless the whole header needs to be included.
Further reading: When can I use a forward declaration?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With