user5549921
user5549921

Reputation:

Class field not accessible inside of function

I'm fairly stupid when it comes to C++ as I'm from a pure Java background with good Python knowledge, but I am trying to make a simple C++ class with a vector referenced in the header file, and access it in a function in the source file. I can access it fine in the constructor, however as soon as I use a function, it apparently doesn't exist according to Eclipse CDT, and the build chain.

Header file (simulator.h):

#ifndef GAME_PHYSICS_SIMULATOR_H_
#define GAME_PHYSICS_SIMULATOR_H_

#include <vector>

#include "../world/object.h"

class simulator {
public:
    simulator();
    virtual ~simulator();

    void add_object(object o);

private:
    std::vector<object> objects;
};

#endif /* GAME_PHYSICS_SIMULATOR_H_ */

Source file (simulator.cpp):

#include "simulator.h"

simulator::simulator() {
    object o;
    objects.push_back(o);   // Works fine in terms of acknowledging the existence of 'objects'.
}

simulator::~simulator() {}

void add_object(object o) {
    objects.push_back(o);   // Immediately throws error saying 'objects' doesn't exist.
}

The funny thing is though, is that I can access things like int's or std::string's fine. As soon as I try to use the vector it breaks. Any ideas?

Upvotes: 0

Views: 444

Answers (2)

Hayt
Hayt

Reputation: 5370

Compared to Java you can define functions outside of the class definition (like in an extra .cpp file, which is usually encouraged to do so), in this case you have to prepend class_name:: to the function signature.

If not, because your function is not in the class namespace, it becomes a non-member function (meaning a function which belongs to no class) and it does not know the objects member which is inside your simulator class.

Upvotes: 2

stijn
stijn

Reputation: 35901

Use simulator::add_object since it's a class method, just like you did for the constructor and destructor already.

Upvotes: 3

Related Questions