Error: expected ')' before token '*' in header
I am doing a program where there is a Hero who has a Sword. I have a class for both. In the title, I get the error: expected ')' before '*' token
in the line Sword(Hero* h);
in the title of the Sword. Here is the competition 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 am using Code :: Blocks.
I've looked at other posts and couldn't find anything that would help, so any data 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
source to share
You cannot include Sword.h from Hero.h and Hero.h from Sword.h, the inclusion chain must stop somewhere. You can use 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 Hero
in Sword.h. The compiler only needs to know what Hero
is class
.
You can do the same in Hero.h: replace #include <Sword.h>
with class Sword;
. Then you can include the files in the corresponding .cpp files where you need definitions in order to use the classes.
Rule of thumb : Always use a forward ad unless you need to include the entire headline.
Further reading: When can I use forward ad?
source to share