I am creating a simple test entity-component system. I have a base Component
class with several derived classes. I then have several systems that apply some logic to these components.
// Component.h
// ------------
class Component
{
public:
Component();
~Component();
}
// ControlComponent.h
// -------------------
#include <string>
#include "Component.h"
class ControlComponent : public Component
{
public:
std::string input = ""; // store simple input instruction
ControlComponent();
~ControlComponent();
};
// ControlSystem.cpp
void ControlSystem::update(Entity* entity)
{
vector<Component*>* components = entity->getComponents();
for (Component* component : *components)
{
PositionComponent* pc = static_cast<PositionComponent*>(component);
ControlComponent* cc = static_cast<ControlComponent*>(component);
if (pc != nullptr && cc != nullptr)
{
std::cout << "Which direction would you like to go?" << std::endl;
std::string input;
std::cin >> input;
cc->input = input; // application breaks here
// Apply some logic...
}
}
}
When I static_cast
from base Component*
to either of the derived components (PositionComponent*
or ControlComponent*
) and when both results are not nullptr
(i.e the cast was successful), I get invalid values, like cc->input
not being able to read characters from string etc.
I wire up the components in my entity factory, like this:
void EntityFactory::wireUpPlayer(Entity* player)
{
player->addComponent(new HealthComponent());
player->addComponent(new ControlComponent());
player->addComponent(new PositionComponent());
}
And the implementation for addComponent is as follows:
void Entity::addComponent(Component* component)
{
m_components.push_back(component);
}
These components are shown to have valid memory addresses, so I'm not sure where the issue is coming from.