Maxim Neaga Maxim Neaga - 1 month ago 19
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 {
private:
int numOfRobots;
int numOfObstacles;

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

public:
Robot *robots;
Obstacle *obstacles;

// constructor
Environment();

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++) {
robots[i].draw();
}
}


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
{
private:
    static int maxRobots;
public:
    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::setMaxRobots(5);

Environment *env = new Environment;
env->printMaxRobots();
delete env;