Looking at making a GUI library for a game engine. I generally avoid pointers if I don't need them and in my below example I find that I don't and it works, but just curious if this design is generally considered good practice or if anyone has comments on it.
int main()
{
// all widgets are positioned and sized according to the window size
Window wndOptions("wndOptions");
Button cmdExit("cmdExit");
// the window doesn't own the widgets nor does it create the widgets so it's not responsible for deleting the widgets
wndOptions.AddWidget(&cmdExit);
// this is how you can find a control and get it casted also. make your variable a reference
Button& test = wndOptions.FindWidget<Button>("cmdExit");
test.SetPosition(50, 25);
return 0;
}
As you can see the idea is that you create your controls (button in this case) and pass a pointer to them to the Window. Then you can find the control by name returning a reference to that control in which you can manipulate the control. It's a bit pointless to use FindWidget() in this example since I have the cmdExit variable, but if I was to pass the window around this would be a way to find and use controls.
The biggest issue I have is that FindWidget() might not find a widget. Right now I throw an exception as not finding a control I would deem as a true exception and not something that should happen much if at all.
Any comments about the usage being done this way?
Button& test = wndOptions.FindWidget<Button>("cmdExitoopsie");
? What do you return if I ask for something not there?dynamic_cast
on an invalid (dangling) pointer is undefined behavior. It might throw an exception on your specific compiler, platform and build configuration (I guess "debug" in MSVC?). But it's neither guaranteed to nor required to, it might pretty well just crash your program.