tamtaasatiani/tahmlib

Incapsulate init

Closed this issue · 3 comments

Hi! I watched your YouTube video and you said

User doesn't need to access it

about void init(void);
So I suggest you to hide init function under modifier private, also I'd suggest hide default constructor too and make public static create function that will return a smart pointer if succeeded and nullptr otherwise and also incapsulate SDL_Window*. Also with smart pointers you don't need to manually delete it, it automatically deletes himself for you when it meets end of scope (deferred destruction)

#include <memory>
class Window
{
	struct Private { explicit Private() = default; };
public:
	Window(Private, const char* title, const int width, const int height)
	{
		this->title = title;
		this->width = width;
		this->height = height;
	}
	~Window()
	{
		if (SDLWindow)
		{
			SDL_DestroyWindow(SDLWindow);
			SDLWindow = nullptr;
		}
	}

	static std::unique_ptr<Window> create(const char* title, const int width, const int height)
	{
		auto ptr = std::make_unique<Window>(Private(), title, width, height);
		ptr->init();
		return ptr;
	}

	SDL_Window* getSdlWindow() const
	{
		return SDLWindow;
	}

private:
	void init(void);

	SDL_Window* SDLWindow;

	const char* title = "Untitled";

	int width = 400;
	int height = 400;

	int flags = 0;
};

* std::unique_ptr+std::make_unique/std::shared_ptr+std::make_shared are interchangeable
* Functions defined here you can move to cpp file and leave only declarations
* struct Private here is private so public constructor wouldn't be accessible from outside without making it private, this is for std::make_unique/std::make_shared, they need a constructor. Alternatively you can make ctor private without struct Private and instead of std::make_unique<Window>(Private, title, width, height) write std::unique_ptr<Window>(title, width, height)

P.S. This is not good code practices or guidelines or something like that, I don't know your codestyle, your dos and don'ts, it's just my suggestions with my codestyle
Edit: Edited create because out of habit I checked init as it should return bool

we have something like:

class Tahm 
{
      class Window
       {
           void init();
       }
}

if init is private, the tahm class won't be able to access it either. which is not what we want. we want "init" to be accessible within the tahm class, but not outside of it
thus, this will not solve the issue i believe

If you want to call init multiple times and only from Tahm, you could make Tahm friend of Window. If not, it called once inside create during allocation anyways (like in RAII):
Remove window = new Window from Tahm::Tahm and replace window->init() with window = Window::create() in Tahm::init

making tahm a friend of window would work, thanks!
calling it inside create won't work because create is called optionally and by the user to assign a title and dimensions to the game window