error C2504: 'Entity': base class undefined - c++

After searching on nearly every page covering this error, I couldn't find a solution that matched my problem. When including the header file for the base class in the file of the derived class, I get the error: "error C2504: 'Entity': base class undefined". I have three classes, a parent class, derived class, and an inbetween class that both of the other classes need access to. I'm making an entity class for my enemies and other entities to inherit from, but even after including its header, I still get the error. I've tried forward declarations for the parent class and they don't seem to do anything to no avail. Before looking at my code, ignore common.h, player.h, skeleton.h, game.h, and resourcemanager.h. Without futher ado, here is my code:
(Entity.h)
#include "Common.h"
#include "Tile.h";
class Entity {
public:
Tile *isSideColliding(bool isSolid, string&& type);
Tile* isTopColliding(bool isSolid, string&& type);
Tile* isBottomColliding(bool isSolid, string&& type);
Sprite sprite;
RectangleShape topHitbox, bottomHitbox;
};
(Slime.h)
#pragma once
#include "Common.h"
#include "Game.h"
#include "Entity.h"
#include "Tile.h"
#include "ResourceManager.h"
class Slime: public Entity {
public:
static vector<Slime> slimeVector;
Slime(float& x, float& y);
static void draw();
static void update();
private:
static const Vector2f SPRITE_DIMENSIONS;
char dir;
//Sprite sprite;
//RectangleShape topHitbox, bottomHitbox;
/*Tile* isSideColliding(bool isSolid, string&& type);
Tile* isTopColliding(bool isSolid, string&& type);
Tile* isBottomColliding(bool isSolid, string&& type);*/
static const float GRAVITY;
static const Vector2f TERMINAL_VELOCITY;
Vector2f position, velocity;
};
(Tile.h)
#pragma once
#include "Common.h"
#include "Player.h"
#include "Skeleton.h"
#include "ResourceManager.h"
#include "Chest.h"
#include "Slime.h"
class Slime;
class Player;
class Skeleton;
class Tile {
public:
Sprite sprite;
static void draw();
static void createLevelPathing();
static void setupBackground();
static vector<Tile> tileVector;
Vector2f spriteDimensions;
bool isSolid;
string type;
private:
Tile(float& x, float& y, string&& type, bool isSolid);
Tile(int& x, int& y, bool isSolid);
static void initTiles(int& levelPosX, int& levelPosY, const Image& image);
static Image getRoomTemplate(int& templateType);
static const float POSITION_SCALAR, SCALE;
static const int START_TILE, DOWN_TILE, UP_TILE, UP_AND_DOWN_TILE, DOOR_TILE;
};
My goal is to inherit from entity to slime. I'm fairly sure my file setup is good though. Could anyone please help explain why I'm getting the error of no base class defined? Also, I would appreciate critisism on my file including and how I could better structure it. Thanks!

As Jerry pointed out in the comment, it is circular include.
This normally implies that something can be improved in the design.
For example, why does the Entity has to care about the colliding logic? Can it instead expose some functions for the Tile module to calculate colliding?
Come back to your question. I suggest to:
In Entity, forward declare the Tile class. Move the #include "tile.h" to the .cpp file. Do the same for Slime.
In Tile, remove the #include and forward declaration for Entity and Slime, it seems they're completely unused there.
Again, I still believe it is better to rethink the flow and the responsibility of classes, which one does what. From what I can remember, circular dependencies will likely bite us later.

Related

Getting 'undeclared identifier' when using vector of type class

Having trouble understanding why I'm getting an 'undeclared identifier' error when I've made sure to include the header file that has the declaration of the class I'm making a vector of.
#pragma once
#include <vector>
#include "Member.h"
class Party {
private:
std::vector<Member> members;
public:
Party();
int get_party_size();
void add_member(Member new_member);
Member& get_member(int num);
};
Here's "Member.h"
#pragma once
#include <vector>
#include <string>
#include "Party.h"
class Member
{
private:
int hp;
bool is_stunned;
bool is_alive;
public:
Member();
~Member();
int get_hp();
bool get_is_stunned();
bool get_is_alive();
void take_damage(int amt);
void stun();
virtual void turn(std::vector<Party>& parties, int my_party, int my_member_number);
virtual std::string get_class_name();
};
Pretty new to the language, so sure I'm missing something obvious.
You have circular dependency between Member and Party
Remove the line
virtual void turn(
std::vector<Party>& parties,
int my_party,
int my_member_number);
in Member and remove the #include "Party.h" in Member.h
Instead think along the lines that a Party is just a collection of Members so there is no need for an individual Member to know about the container
So after input from #some-programmer-dude you could also solve it by adding a forward declaration in your Member.h instead of including the Party.h
class Party;
class Member { ... }

Circular Inclusion using Singleton and child class

While working on a little game of mine, I ran into a circular dependency related issue.
Say I'm using 2 classes and a helper namespace(all include guarded), where Base is the main game class, Player the player object and a child of Entity, and helper a functional namespace responsible for handling tile collision:
When I try to compile the code, Player is not recognized as a type-specifier in base.h and I also get an unknown override specifier. When I forward declare Player it is undefined, although I am including player.h.
I've been questing on the internet for a solution, but none of the typical solutions to circular inclusion seemed applicable. As aforementioned I have tried all sorts of combinations of forward-declarations but it only changed the type of error.
I was wondering whether anyone could notice any flaw in the code below.
(Please note that I've put all of the function implementations in the headers for demonstration purposes only, they've got their own little cpp files)
base.h
#include "player.h"
#include "level.h"
class Base{
static Base& instance()
{
static Base base;
return base;
}
Player player;
Level level;
}
entity.h
class Entity{
vec2 velocity; //Assume we are using the glm library
vec2 position;
virtual void update()
{
}
}
player.h
#include "helper.h"
#include "entity.h"
class Player:public Entity{
void update()
{
velocity=helper::tileCollision(velocity);
//Update position and stuff
}
}
helper.h
#include "level.h"
#include "base.h"
namespace helper{
vec2 tileCollision(vec2 velocity)
{
Level& level = Game::instance().level;
//Pop some fancy tile collision math in here
return vec2(0);
}
}
The first of all, please don't write implementations of functions in headers unless it is not inline or template.
Try the following:
base.h
#include <memory>
class Player;
class Level;
class Base {
public:
static Base& instance();
private:
Base();
unique_ptr<Player> player;
unique_ptr<Level> level;
}
base.cpp
#include "base.h"
#include "player.h"
#include "level.h"
Base::Base() : Player(make_unique<Player>()), Level(make_unique<Level>())
{
}
static Base& Base::instance()
{
static Base base;
return base;
}
And you should watch the following :
https://www.youtube.com/watch?v=QjFpKJ8Xx78

Don't understand why I am getting an unresolved external symbol?

I don't understand why I am getting an unresolved external symbol in this specific example.
I have a Rectangle struct defined in a header file.
I have a Level class which has a pointer to a Player class as the Level creates a new player.
I my Player class, the constructor takes in a pointer to it's current level.
So since my Level includes Player.h I forward declare Level in my Player class to prevent a circular reference.
However, when I try and add a Rectangle member variable to my Player class - I get the unresolved external symbol error, but I can't see why - since the Player class includes the header - and the definition is in the header. It works fine in my Level class.
Also - if I change the member variable to a pointer it links fine.
Can someone explain to me why this is the case and how I can fix the issue?
// Rectangle.h
#pragma once
namespace Test
{
struct Rectangle
{
public:
Rectangle();
Rectangle(
int x,
int y,
int width,
int height) :
X(x),
Y(y),
Width(width),
Height(height)
{
}
int X;
int Y;
int Width;
int Height;
};
}
// Level.h
#pragma once
#include "Player.h"
#include <memory>
namespace Test
{
class Level
{
public:
Level()
{
_player.reset(new Player(this));
};
private:
std::unique_ptr<Player> _player;
};
}
// Player.h
#pragma once
#include "Rectangle.h"
namespace Test
{
class Level;
class Player
{
public:
Player(
Level* currentLevel) :
_currentLevel(currentLevel)
{
}
private:
Level* _currentLevel;
// This line causes the issue
Rectangle _localBounds;
};
}
You forgot to add braces on your Rectangle constructor. Make it like this:
Rectangle() {}
So the problem is you have the definition but not the implementation. You can indeed declare a function without braces but it is like you make a promise to the compiler that you are going to add the function's body somewhere else. That's why separating classes to .hpp and .cpp files works.
Note: Retired Ninja gave the answer first in a comment below the post.

Class Type Redefinition C++

I have seen other people asking this question before, but the answers they received were unique to their programs and unfortunately do not help me.
Firstly, I have a shape class - split into .h and .cpp files
//Shape.h
#include <string>
using namespace std;
class Shape
{
private:
string mColor;
public:
Shape(const string& color); // constructor that sets the color instance value
string getColor() const; // a const member function that returns the obj's color val
virtual double area() const = 0;
virtual string toString() const = 0;
};
//Shape.cpp
#include "Shape.h"
using namespace std;
Shape::Shape(const string& color) : mColor(NULL) {
mColor = color;
}
string Shape::getColor() const
{
return mColor;
}
I keep getting an error in my Shape.h class that says 'Shape' : 'class' type redefinition.
Any idea why I might be getting this error?
add include guard to your header file
#ifndef SHAPE_H
#define SHAPE_H
// put your class declaration here
#endif
And the way you initialize member mColor is incorrect. You can't assign NULL to string type
Shape::Shape(const string& color) : mColor(color) {
}
Add virtual destructor to Shape class as it serves as a base with virtual functions.
Also, do NOT use using directive in header file.
It seems like you want to write an abstract base class here, but is there any other files you compiled but not showed here?
You must include “shape.h” twice more.
Just use macros to prevent this case.
PS:I guess Rectangle is base class of Square,and also inherited Shape.

Inheritance error dilemma: "invalid use of incomplete type" VS "expected class-name"

So I'm trying to get class "Herder" to inherit from class "Mob". But I am getting compiler errors that read as follows:
error: invalid use of incomplete type 'struct Mob'
error: forward declaration of 'struct Mob'
This is what Herder.h looks like:
#ifndef HERDER_H_INCLUDED
#define HERDER_H_INCLUDED
#include <SFML/Graphics.hpp>
#include <cstdlib>
#include "Level.h"
#include "Mob.h"
class Mob;
class Herder : public Mob
{
public:
//Member functions.
Herder(Level* level, int x, int y);
void virtual GameCycle(sf::RenderWindow* App);
void virtual Die();
void Roar();
protected:
float m_RoarCountdown;
float m_RoarTime;
float m_Speed;
bool m_Roaring;
};
#endif // HERDER_H_INCLUDED
Figuring that it must be the class Mob; that is causing this, I remove it, but then I get the following error, refering to the line where the curly braces open:
error: expected class-name before '{' token
This is actually why I originally added the forward declaration - I had thought that the compiler wasn't recognizing Mob in class Herder : public Mob, so I figured I would forward declare.
I don't think it's a case of cyclical dependency, as has been the case in some cases I found via Google - "Mob.h" contains nothing to do with the Herder class whatsoever.
I have tried removing #include "Mob.h" altogether and sticking with just the forward declaration, but that doesn't work either - I get only one error, again:
error: invalid use of incomplete type 'struct Mob'
This is confusing. I've successfully gotten classes to inherit before, and this code seems analogous in all relevant ways to my previous successful attempts.
EDIT: Here are the contents of Mob.h
#ifndef MOB_H_INCLUDED
#define MOB_H_INCLUDED
#include <SFML/Graphics.hpp>
#include <cstdlib>
#include "Level.h"
class Level;
class Mob
{
public:
//Member functions.
Mob(Level* level, int x, int y);
float GetX();
float GetY();
void SetColor(sf::Color color);
void virtual GameCycle(sf::RenderWindow* App) = 0;
void virtual Die() = 0;
void Draw(sf::RenderWindow* App);
protected:
float m_X;
float m_Y;
bool m_Moving;
int m_Health;
sf::Sprite m_Sprite;
Level* pLevel;
};
#endif // MOB_H_INCLUDED
EDIT: Here are the contents of the "Level.h" file. Note that Baby is a child class of Mob in much the same way as Herder; both experience the same errors.
#ifndef LEVEL_H_INCLUDED
#define LEVEL_H_INCLUDED
#include <SFML/Graphics.hpp>
#include <cstdlib>
#include "Tile.h"
#include "Herder.h"
#include "Baby.h"
class Tile;
class Herder;
class Baby;
/// LEVEL
/// This is the collection of all data regarding a level, including layout, objects, mobs, and story elements.
///
class Level
{
public:
//Constructor
Level(int height, int width, std::string name);
//For obtaining positional data
int GetHeight();
int GetWidth();
std::string GetName();
sf::Image GetTileImage(int image);
sf::Image GetMobImage(int image);
std::vector< std::vector<Tile> >& GetGrid();
void NewHerder(int x, int y);
void NewBaby(int x, int y);
void GameCycle(sf::RenderWindow* App);
void GraphicsCycle(sf::RenderWindow* App);
private:
//Size
int m_Height;
int m_Width;
//Spatial coords
std::string m_Name;
//The grid of tiles.
std::vector< std::vector<Tile> > m_Grid;
//A vector of the images to be used for tiles.
std::vector<sf::Image> m_TileImages;
//A vector of the images to be used for tiles.
std::vector<sf::Image> m_MobImages;
//The herders
std::vector<Herder> m_Herders;
//The babies
std::vector<Baby> m_Babies;
};
#endif // LEVEL_H_INCLUDED
EDIT: Pre-emptively, here are the contents of Tile.h:
#ifndef TILE_H_INCLUDED
#define TILE_H_INCLUDED
#include <SFML/Graphics.hpp>
#include <cstdlib>
#include "Level.h"
class Level;
/// TILE
/// This is the basic environmental unit in the game
///
class Tile
{
public:
//Constructor
Tile(int col, int row, int size, int type, Level* level);
//For obtaining positional data
int GetX();
int GetY();
int GetRow();
int GetCol();
//For obtaining type data
int GetType();
//For obtaining string type data
std::string GetStringType();
//For changing type data
void SetType(int type);
void SetStringType(std::string character);
//For activities that regularly take place
void GameCycle();
//Draws the tile.
void Draw(sf::RenderWindow* App);
private:
//The level this tile belongs to.
Level* m_Level;
//Size (it's a square!)
int m_Size;
//Spatial coords
int m_X;
int m_Y;
//Grid coords
int m_Row;
int m_Col;
//Type
int m_Type;
//Visual data
sf::Sprite m_Tile;
};
#endif // TILE_H_INCLUDED
It is a cyclic dependency (Herder.h includes Level.h which includes Herder.h, etc.).
In Herder.h, simply replace this :
#include "Level.h"
with :
class Level;
and do the same in Mob.h
The general rule is to include as little header files as possible (ie. only the ones you need). If you can get by with a forward declaration eg., then use that rather than a full include.
The problem you have is a cyclic dependency which is a code smell. On the one side, to be able to derive from a type, the base definition must be available to the compiler (i.e. the compiler requires a fully defined type from which to inherit). On the other hand your base class depends on the derived class.
The technical answer is to forward declare the derived type (so that you can define the base), and then define the base. But you should really think on what you are doing: why are those two separate types related by inheritance? Why not one? Or three (split responsibilities)? If the base depends on the derived for it's own interface, that seems to indicate that they are too highly coupled. Rethink the design.
"Herder.h" and "Level.h" are #include in each other. So, I think this error is coming from the "Herder.h" which is included first. It's becoming cyclic. Remove that and see if the error goes away.