SFML community forums

General => General discussions => Topic started by: mpaw on May 24, 2020, 04:42:14 pm

Title: Init of static member object
Post by: mpaw on May 24, 2020, 04:42:14 pm
Hi.

I have class in which I have static member, which is RenderWindow object. How can I initialize it?

class A
{
  public:
  static sf::RenderWindow window;
};

How Can I init it in my program?
Thanks
Title: Re: Init of static member object
Post by: Athenian Hoplite on May 24, 2020, 05:12:54 pm
Like all other static objects. In your cpp file I'd imagine. 

// Header file
class A
{
  public:
  static sf::RenderWindow window;
};

// Cpp file
sf::RenderWindow A::window;
 

You can use the default constructor and then at runtime use the sf::RenderWindow::create method to (re) create the window with the parameters you somehow got programmatically or replace "= sf::RenderWindow();" with the usual constructor and pass the arguments you want hardcoded.
Title: Re: Init of static member object
Post by: mpaw on May 24, 2020, 05:33:25 pm
I tried, but there is no static constructor defined for RenderWindow :(
Title: Re: Init of static member object
Post by: Athenian Hoplite on May 24, 2020, 05:42:59 pm
What I told you before works. sf::RenderWindow defines more than one constructor which can be used to instantiate static variables the way I described. You can also derive a class from sf::RenderWindow if you prefer but that is beside the point.

Note: C++ doesn't have "static constructors" like in C#.

This works:
class A
{
  public:
  static sf::RenderWindow window;
};

sf::RenderWindow A::window;
 
Title: Re: Init of static member object
Post by: mpaw on May 24, 2020, 05:56:10 pm
I get error:

... error: use of deleted function 'sf::RenderWindow::RenderWindow(const sf::RenderWindow&)'|
... note: 'sf::RenderWindow::RenderWindow(const sf::RenderWindow&)' is implicitly deleted because the default definition would be ill-formed:|
Title: Re: Init of static member object
Post by: Athenian Hoplite on May 24, 2020, 06:05:18 pm
What code is producing that error ? I have compiled the code with no errors so this is not what is giving you that.
Title: Re: Init of static member object
Post by: Laurent on May 24, 2020, 07:18:32 pm
Just

sf::RenderWindow A::window;

No need to copy-construct from a default-constructed instance ;)
Title: Re: Init of static member object
Post by: Athenian Hoplite on May 24, 2020, 07:39:43 pm
Just

sf::RenderWindow A::window;

No need to copy-construct from a default-constructed instance ;)
whoops-a-daisy ;D ;D
edited
Title: Re: Init of static member object
Post by: eXpl0it3r on May 26, 2020, 11:59:22 am
Beyond that, you should not use static variables for SFML resources, as the initialization and destruction order of static/global variables is undefined and can lead to crashes.