I handed in a remake of an old game in C++ using SDL2 for a programming course that I took, I passed but the professor left me some feedback and there is one part that I couldn't understand. It made sense when he said it and when I tried implementing it I got stuck.
I have an Enemy
class which is an abstract class and then many different enemies that inherit from that class. The issue is that when I am creating an enemy I have to pass in its constructor my ProjectileManager*
instance that I have created in my main controlling file called Game.cpp. He said that since all enemies need the ProjectileManager it would be smarter to just add it in the Enemies
class as protected and have the other children inherit it.
The issue is that the instance is created in the Game.cpp and I have to pass that specific instance since that is the one that I am Drawing and Updating for. Is there a way to do that?
Edit: Here is some of the code
Game.cpp:
void Game::Initialize()
{
m_pProjectileManager = new ProjectileManager();
}
The projectile manager is what Updates and Draws all the projectiles as well as their hit logic etc. It has an array that manages all the projectiles. Every time an enemy wants to shoot it would access the projectile manager (that I passed in its constructor) and trigger the shoot function of the specific enemy:
void Plant::Shoot(const Point2f& target)
{
if (m_CanShoot)
{
m_CurrentState = Plant::PlantState::shooting;
m_pProjectileManager->AddProjectile((new PlantProjectile(Point2f{ m_Shape.left, m_Shape.bottom }, target)));
m_CanShoot = false;
m_TimeSinceLastShot = 0;
}
}
Finally this is the Enemy class that I have right now:
class Enemies
{
public:
virtual ~Enemies() = 0;
virtual void Update(float elapsedSec, const Point2f& playerPos, Level& level) = 0;
virtual void Draw() const = 0;
virtual Rectf GetShape() const = 0;
virtual float GetHealth() const = 0;
virtual void Damage(float damage) = 0;
protected:
ProjectileManager* m_pProjectileManager;
};