0

Can anyone tell me how I can use object that I defined in main like this

int main()
{
sf::RenderWindow window;
}

And now I want to use window object in class that I made. But it must point out to the same main's window. How can we use it? Can anyone explain it with some code example?
I am using SFML library of C++.

Max Daniel
  • 45
  • 1
  • 4

2 Answers2

2

You can pass them as references or pointers, ex.:

class CEngine {
  sf::RenderWindow& window;
public:
  CEngine(sf::RenderWindow& wnd) : window(wnd) {}
  // ...
};

int main()
{
sf::RenderWindow window;
CEngine engine(window);
}
marcinj
  • 48,511
  • 9
  • 79
  • 100
1

There are several solutions to making objects created in main available to other code:

  • Pass the window as a parameter, by pointer or by reference, to code that needs to use it
  • Make a singleton object that holds a pointer to the window, use that object throughout your code, and set its pointer in main before calling any other code
  • For the sake of completeness, you can make a global variable pointing to your object in main. This is not a good recommendation.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523