Maxim Neaga
Maxim Neaga

Reputation: 961

C++ How to access an object initialized in main() from outside of main()?

My main() looks like this:

   int main(int argc, char** argv)
    {
    // Initialize GLUT
    glutInit(&argc, argv);

    ...

    glutDisplayFunc(display);
    ...

    // Set robot's parameters
    Robot robot; // Initialize global object robot
    robot.setSize(50);
    robot.setColor('G');
    robot.setLocation(50,100);

    glutMainLoop();
    return EXIT_SUCCESS;
}

Then I have another function, which I would like to have access to the methods of the robot:

// This function is constantly "looped"
void display() {
    ...
    robot.draw();
    ...
}

What is the legit way to do it in C++?

Upvotes: 0

Views: 472

Answers (2)

Qaz
Qaz

Reputation: 61910

For anyone interested, the question changed, so my old answer is lost to the edits.

If your display function is required to have a specific signature (void()), you can use std::bind, presuming you have access to C++11:

void display(Robot &robot){...}

//in main
Robot robot;
glutDisplayFunc(std::bind(std::ref(display), robot));

If you don't have C++11, boost::bind works just as well:

glutDisplayFunc(boost::bind(boost::ref(display), robot));

If you have neither, you'll have to store robot more globally.

Upvotes: 3

IronMensan
IronMensan

Reputation: 6831

Since the glut display callback doesn't take parameters, you will have to use a global variable (Robot * gRobot; ) or a singleton pattern.

Upvotes: 1

Related Questions