1

I have been attempting to make some code, but I am a bit new to c++ and need some help. I cannot instantiate class Player as a pointer, because it's an "incomplete type" (or undefined type, vs says both). Below are some (simplified, albeit not very) versions of my code:

Entity.h

#pragma once
#include <vector>
class Entity
{
public:
    static void init();
    class EntityObject;
    class Player;
    static std::vector<EntityObject*> entities;
};

Entity.cpp

#include "Entity.h"

void Entity::init()
{
    entities = std::vector<EntityObject*>();
}

class Entity::EntityObject
{
private:
    float velX, velY, x, y;
public:
    EntityObject(float xa, float ya) { x = xa; y = ya; }
    float getVelX() { return velX; }
    float getVelY() { return velY; }
    float getX() { return x; }
    float getY() { return y; }
};

class Entity::Player : EntityObject
{
public:
    Player(float xa, float ya) : EntityObject(xa, ya)
    {
        printf("Player created");
    }
};

Can anyone tell me why

#include "Entity.h"
int main(int argc, char* argv)
{
    Entity::init();
    Entity::EntityObject* player = new Entity::Player(10.0f, 10.0f);
    Entity::entities.push_back(player);
}

gives an incomplete/undefined type? Thanks.

Edit: The errors are: Both errors direct to this line: Entity::EntityObject* player = new Entity::Player(10.0f, 10.0f);

Error (active)  E0070   incomplete type is not allowed
Error   C2027   use of undefined type 'Entity::Player'
nvoigt
  • 75,013
  • 26
  • 93
  • 142
NMorris
  • 72
  • 1
  • 9

2 Answers2

3

You defined the Entity::Player class in the .cpp file, not in the .h file. Therefore, even though the main() includes the .h file, it does not know about Entity::Player.

Eli
  • 693
  • 5
  • 12
1

Entity::Player is forward declared in Entity.h.

When the compiler compiles your main.cpp module, it does not know anything about this class except that it exists, in particular it has no idea that this class as a constructor taking two float : Player(float xa, float ya)

=> Your issue is related to forward declaring, not nested class.

Read this thread to understand your problem What are forward declarations in C++?

Read this one to understand what you can and what you can't do with forward declaration When can I use a forward declaration?

sandwood
  • 2,038
  • 20
  • 38