Mitch
Mitch

Reputation: 25

Vector of Custom Objects

I am trying to create a vector of custom objects defined in a header file and then initialize them in the actual cpp file. I'm getting the following errors in Visual Studio:

error C2976: 'std::vector' : too few template arguments
error C2065: 'Particle' : undeclared identifier
error C2059: syntax error : '>'

In the code below, the vector is defined in Explosion.h.

Particle.h:

#pragma once
class Particle : public sf::CircleShape {
public:
    float speed;
    bool alive;
    float vx;
    float vy;
    Particle(float x, float y, float vx, float vy, sf::Color color);
    ~Particle();
};

Particle.cpp:

#include <SFML/Graphics.hpp>
#include "Particle.h"

Particle::Particle(float x, float y, float vx, float vy, sf::Color color) {
    // Inherited
    this->setPosition(x, y);
    this->setRadius(5);
    this->setFillColor(color);

    // Player Defined Variables
    this->speed = (float).05;
    this->alive = true;
    this->vx = vx;
    this->vy = vy;
}

Particle::~Particle() {
}

Explosion.h:

static const int NUM_PARTICLES = 6;

#pragma once
class Explosion {
public:
    std::vector<Particle*> particles;
    bool alive;
    Explosion();
    ~Explosion();
};

Explosion.cpp:

#include <SFML/Graphics.hpp>
#include "Particle.h"
#include "Explosion.h"

Explosion::Explosion() {
    this->alive = true;

    // Add Particles to vector
    for (int i = 0; i < NUM_PARTICLES; i++) {
        this->particles.push_back(new Particle(0, 0, 0, 0, sf::Color::Red));
    }
}

Explosion::~Explosion() {
}

I'm sure there is something fundamentally wrong here since C++ is fairly new to me.

Upvotes: 2

Views: 1477

Answers (1)

Chad
Chad

Reputation: 19032

You need to tell Explosion.h what a Particle is.

In this case, Explosion.h is using Particle*, so a forward declartion will suffice.

Explosion.h

class Particle; // forward declaration of Particle

class Explosion {
// ...
};

You could also simply #include "Particle.h, however as your projects increase using forward declarations (instead of direct includes) can significantly reduce your build times.

Upvotes: 7

Related Questions