Beginners C++ Q: cannot convert 'this' pointer from 'const UMM2GameInstance' to 'UMM2GameInstance &'

Hi all,

I’m trying to update a private variable via a public function and I am receiving the following error:

Here is the class and implementation…



#include "Engine/GameInstance.h" 
#include "MM2GameInstance.generated.h"

UCLASS()
class UMM2GameInstance : public UGameInstance
{
	GENERATED_BODY()

public:
	UMM2GameInstance(const FObjectInitializer& ObjectInitializer);

	UFUNCTION(BlueprintCallable, Category = "Statistics")
	void IncrementFailedPuzzleAttempts();

	UFUNCTION(BlueprintCallable, Category = "Statistics")
	int32 GetFailedPuzzleAttempts() const;

private:
#pragma region Statistics
	int32 FailedPuzzleAttempts;
#pragma endregion
};




#include "MM2.h"
#include "MM2GameInstance.h"

UMM2GameInstance::UMM2GameInstance(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	FailedPuzzleAttempts = 0;
}

void UMM2GameInstance::IncrementFailedPuzzleAttempts()
{
	FailedPuzzleAttempts++;
}

int32 UMM2GameInstance::GetFailedPuzzleAttempts() const
{
	return FailedPuzzleAttempts;
}


I’m trying to call ‘IncrementFailedPuzzleAttempts()’ from another class like so: MyGameInstance->IncrementFailedPuzzleAttempts(); which is giving me the error.

Kindest Regards,
Matt.

Hello Other Matt,

The compiler is complaining because where ever you have the MyGameInstance* declared, you have it marked as const (and thus it can only call const methods) which IncrementFailedPuzzleAttempts is not. Just a quick review:



MyGameInstance* MyPoint; // A Non-Const pointer to a Non-Const MyGameInstanceObject.
MyGameInstance* const MyPointer; // A Const pointer to a Non-Const MyGameInstance Object.

const MyGameInstance* MyPointer; // A Non-Const pointer to a Const MyGameInstance Object.
const MyGameInstance* const MyPointer; // A Const pointer to a Const MyGameInstance Object.


1 Like