My solution to setting MenuInterface

I understand using a setter like this is good practice:

void UMainMenu::SetMenuInterface(IMenuInterface* MenuInterface)
	this->MenuInterface = MenuInterface;

But the solution I found on my own was this:

bool UMainMenu::Initialize()
    --Some other code--

    MenuInterface = Cast<IMenuInterface>(GetGameInstance());
    return true;

To my understanding these both essentially do the same thing. My question is what is the advantage of using a setter that has to be called from the game instance when it could just be set from the main menu code without ever having to touch the GameInstance’s code other than having it derive from IMenuInterface and adding necessary functions?

1 Like

The advantage of a setter is that it has to be of base type IMenuInterface and you also have the option of having different implementations so your code could be reusable.

The disadvantage of the Initialize you have is easier to explain. You are assuming that a cast succeeds but could easily fail. This would result in a crash. The setter is the safer of the 2 solutions as a result.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms