Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Create a static class to store pointers

I'm trying to learn my way around C++ by making a simple game/engine with SDL2. Currently I'm having some issues trying to make a static class.

I think the easiest way is to just describe what I want to achieve:

  • I want to be able to make a class (called Pointer) which will store pointers to different crucial objects like the window and the renderer.
  • I want to set these values to the Pointer class(private variables), from my main *.cpp file after I have created and initialized the window/renderer.
  • Then I want to be able to use this class to access those objects through getter functions from wherever I might be in the program, but
  • I want them to be static, so that I can access the original values, and not initialize new empty ones.

I hope this was somewhat understandable.

like image 327
coco4l Avatar asked Feb 14 '26 10:02

coco4l


1 Answers

(Pointer is a terrible class name.)

You want a class such that only one instance can exist at a time, and it is accessible to any code that is aware of the class. The solution is the Singleton Pattern. It is a badly overused pattern (novices like to use it as a substitute for global variables) but this is exactly the kind of thing it's good for.

like image 91
Beta Avatar answered Feb 17 '26 00:02

Beta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!