How to cast to initialize object references in C++?

Hi, How to do this properly in C++. I first created the variable of type BP_BaseCharacter and later get the BP_BaseCharacter class and sets the variable CharacterRef.
**

What I am trying to do is using just a pointer to make references but I doubt this is not right because I think I am not casting correctly.

UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = Refference Related)
ABaseCharacter * CharacterRef;
APawn* YourPawn = YourPlayerController->GetPawn();
ABaseCharacter* CharacterRef = Cast<ABaseCharacter>(YourPawn);
if (IsValid(CharacterRef)) {
  // valid cast.
}
3 Likes

Thank You Sir for the fast reply with a perfect solution :slightly_smiling_face:

Sir can You tell me if anything is not right with my this approach.

	ACharacter* GetPlayerCharacter = UGameplayStatics::GetPlayerCharacter(this, 0);
	ABaseCharacter* CharacterRef = Cast<ABaseCharacter>(GetPlayerCharacter);
	if (CharacterRef != nullptr)
	{
		printf("All Ok");
	}
	else
	{
		return;
	}

It’s safest to use IsValid(Character) instead of checking against nullptr only.
Can be written as:

ABaseCharacter* CharacterRef = Cast<ABaseCharacter>(UGameplayStatics::GetPlayerCharacter(this, 0));
if (IsValid(CharacterRef)) 
{
  // this is OK
}
else
{
	return;
}
2 Likes

Ok Thank You, now its all fine )