Max Daniel
Max Daniel

Reputation: 45

How can I use Objects form main in any class? C++

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++.

Upvotes: 0

Views: 95

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726969

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.

Upvotes: 1

marcinj
marcinj

Reputation: 50026

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);
}

Upvotes: 2

Related Questions