Maxim Neaga Maxim Neaga - 7 months ago 44
C++ Question

C++ static member functions and variables

I am learning C++ by making a small robot simulation and I'm having trouble with static member functions inside classes.

I have my Environment class defined like this:

class Environment {
int numOfRobots;
int numOfObstacles;

static void display(); // Displays all initialized objects on the screen

Robot *robots;
Obstacle *obstacles;

// constructor

static void processKeySpecialUp(int, int, int); // Processes the keyboard events

Then in the constructor I initialize the robots and obstacles like this:

numOfRobots = 1; // How many robots to draw
numOfObstacles = 1;
robots = new Robot[numOfRobots];
obstacles = new Obstacle[numOfObstacles];

Here is example of static function that uses those variables:

void Environment::display(void) {
// Draw all robots
for (int i=0; i<numOfRobots; i++) {

When I try to compile, I get error messages like

error: invalid use of member ‘Environment::robots’ in static member function

I tried making numOfRobots, numOfObstacles, robots and obstacles static, but then I got errors like

error: undefined reference to 'Environment::numOfRobots'

I would greatly appreciate of someone could explain me what I am doing wrong.
Thank you!

Answer Source

Static methods can't use non-static variables from its class.

That's because a static method can be called like Environment::display() without a class instance, which makes any non-static variable used inside of it, irregular, that is, they don't have a parent object.

You should consider why you are trying to use a static member for this purpose. Basically, one example of how a static method can be used is as such:

class Environment
    static int maxRobots;
    static void setMaxRobots(int max)
        maxRobots = max;
    void printMaxRobots();

void Environment::printMaxRobots()
    std::cout << maxRobots;

And you would have to initialize on the global scope the variables, like:

int Environment::maxRobots = 0;

Then, inside main for example, you could use:


Environment *env = new Environment;
delete env;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download