Use Class Member By Reference

I would like to operate on a member of my class from a separate .cpp file. At the moment i am getting an error.

Oh and don't worry about the UFUNCTION/UPROPERTY Macros, they're just for Unreal Engine 4.

Error

error:a nonstatic member reference must be relative to a specific object

Member I want to use, located in DungeonExplorerCharacter.h
1
2
  UPROPERTY(EditAnywhere, BluePrintReadWrite, Category = Key)
	int32 Keys;


The function that uses the member
1
2
3
4
5
6
// On collisions, this function will be called.
void AKeyItem::OnOverlap(class AActor * OtherActor, UPrimitiveComponent * OtherComp, int32 HitResult, bool Impulse, const FHitResult& Overlap)
{
	ADungeonExplorerCharacter::Keys += 1;
	Destroy(false, true);
}
ADungeonExplorerCharacter::Keys += 1; You do not have object instance here. You are trying to access member though class name. It is possible only for static members.

You either need an instance of object or make mamber static.
What if i need to do this using pointers, so i can act upon the object directly. I.E I want to change that classes values.

Trying to create a pointer to the class throws me an error.
ADungeonExplorerCharacter *MyCharacter;
Gives me
error C4700: uninitialized local variable 'MyCharacter' used
ADungeonExplorerCharacter *MyCharacter; This is just a pointer. It does not point to anything and unless you will point it to valid object, using it will cause undefined behavior. Error you getting is probably one of the Visual Studio safeguards against common mistakes.

I would suggest to use references instead of pointers. They are safer. Example of use:

1
2
3
4
5
6
7
8
9
10
void addKey(ADungeonExplorerCharacter& character)
{
    character.Keys += 1;
}

/*...*/

ADungeonExplorerCharacter player;
//...
addKey(player);
Topic archived. No new replies allowed.