Problem with C++ casting

Hey, I would need a little help from someone, since 4.14 my code doesn’t work right, I tried everything but this cast seems to resist everything, it would be cool if someone could help me:
here is the broken code:

ABaseGameMode * UStaticFunctionLibrary::GetGameModeCDO(UObject * WorldContextObject)
{
	AGameStateBase * GameState = UGameplayStatics::GetGameState(WorldContextObject);
	if (GameState)
	{
		ABaseGameMode Cast = Cast<ABaseGameMode>(GameState->GetDefaultGameMode());
		return Cast;
	}

	return NULL;
}

here are the error i keep getting :

i hope someone can help me ! :smiley:

GetDefaultGameMode() returns const AGameModeBase*, and so Cast() will return const ABaseGameMode*. But you are trying to return it a non-const ABaseGameMode*.

You need to return const ABaseGameMode*.

Or cast away constness by a const_cast, but you probably don’t want to do that.

Steve

het thx for the answer, but I think the best option is to do a const_cast because I can’t change the return type to a const, if I do that I get a ton of errors, so yeah. the problem I have is that I get a weird error with the const_cast :

Unlike UE4’s Cast, C++'s const_cast requires you to put the asterisk to say that you’re wanting a pointer. What you need is:

const_cast<ABaseGameMode*>

The other errors you get will be because any code which calls GetGameModeCDO() will also need const-correcting:

// error: this needs to be const ABaseGameMode*
ABaseGameMode* GameMode = Library->GetGameModeCDO(Context);

… and so on, throughout the project:

https://isocpp.org/wiki/faq/const-correctness#retrofitting-const

This was added as an important safety feature, as it is not safe to modify CDOs. I would advise only doing the const_cast if you are absolutely sure that you’re never going to be modifying the CDO via that returned pointer.

Steve

hey thanks for the complete answer you gave me, ut i’ll need you for a last thing :D, i tried doing it as you said, without the Cont_cast, but it is a staticfunctionlibrary so i decided to return to the first idea i had and to do a const_cast, i followed your step and now i have this problem ;

You need both const_cast and Cast:

const_cast<ABaseGameMode*>(Cast<ABaseGameMode>(GameState->GetDefaultGameMode()));

Steve

1 Like

OHHH, ok i understand how it works now !! thanks for all the help !