derived class reference to derived class

Hi

I have the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <cstddef>
#include <iostream>
#include <vector>


class Entity;
std::vector<Entity*> entities = std::vector<Entity*>();

class Component;
class Entity
{
   private:
      std::vector<Component*> comps = std::vector<Component*>();

   public:

      ~Entity()
      {
         for(size_t i = 0; i < comps.size(); i++)
            delete comps[i];
      }

      template <typename T>
      T& AddComponent()
      {
         T* comp = new T();
         comp->entity = this;
         comps.push_back(comp);
         return *comp;
      }

};

class Component
{
   public:
      Entity* entity;
};

template <typename T>
T& CreateEntity()
{
   T* entity_t = new T();
   entities.push_back(entity_t);
   return *entity_t;
}

class Enemy : public Entity
{
   public:
      int TEST = 43;
};

class ComponentTester : public Component
{
   public:
      ComponentTester()
      {
         std::cout << "TEST: " << this->entity->TEST <<  '\n';
      }
};

int main(int argc, char** argv)
{
   Enemy e = CreateEntity<Enemy>();
   ComponentTester t = e.AddComponent<ComponentTester>();
   
   //Health h = e.addComponent<Health>();
   //Health h2 = e.getComponent<Health>();

   //Delete entities
   for(size_t i = 0; i < entities.size(); i++)
      delete entities[i];

   return 0;
}




If i try and compile it right now it'll give me and error and tell me that Entity does not have a member "TEST"

Is there a way to make any class that derives from "Component" to have a reference to the kind of class that derives from "Entity".

So that component can access public members from its entity "parent"
Because Component contains a pointer to an Entity, it only knows about things that are in Entity--things that are common to ALL Entity subclasses. The Enemy class derives from Entity, so it contains everything in an Entity PLUS more stuff (in this case, TEST).

If you want to access TEST from within Component, then change the pointer to Enemy* entity;. Or, move TEST into the Entity base class. Otherwise, you are stuck accessing only things that are common to all Entities. At beginner levels of programming there is no way to know whether the object pointed to by Component::entity is an Enemy, and base class Entity, or something else derived from Entity.
In addition, the code has undefined behaviour because Entity does not have a virtual destructor.

Strongly consider using std::unique_ptr<> instead of raw owning pointers.
http://en.cppreference.com/w/cpp/memory/unique_ptr
Registered users can post here. Sign in or register to post.