How do I call an actor's C++ function from another class?

So I have this line of code which lets me get the player class from the door class:

Player = Cast(()->GetFirstPlayerController()->GetCharacter());
This lets me get the player class and call any functions I create in it.

But when I try to get the door that the player is interacting with, this line of code gives me errors:

Door = Cast(GetDoorInteractingWith());

GetDoorInteractingWith() returns an AActor pointer and GetCharacter() returns an ACharacter pointer, so when I cast the APlayerCharacter class to an ACharacter pointer it works fine, but when I try to cast the ADoor class to an AActor pointer it doesn’t work!

APlayerCharacter is an ACharacter and ADoor is an AActor.

What am I doing wrong here?

Is your Door member/variable of class ADoor or AActor?
Right now you call GetDoorInteractingWith() returning AActor, then you cast to ADoor but I can’t see whether the assignment is correct afterwards.

Apart from that, why don’t you just return an ADoor pointer from GetDoorInteractingWith() and save yourself the Cast?

Here how you can cast and check validity of a cast :

if(auto Door = Cast<ADoor>(GetDoorInteractingWith())
{
    Door->SpecialDoorMethod(); // here the object returned by GetDoorInteractingWith has been sucessfully casted to a door;
}

Turns out I had a circular dependency including door.h in player.cpp and player.h in door.cpp.

I’ll figure out a new way of doing what I was trying to do by just including player.h in door.cpp…

If you do that, you may have to declare your player class in your door header. This is called forward declaration, so if you run into problems, perhaps this info helps.

Thank you for the tips! It definitely helps. I had forward declared the player class in the door header without knowing exactly why, but I’m now doing research to better understand why I’m doing this. (I just learned about friend classes because of this too!)

You function should return ADoor* without need of any casting

Circular reference only involves header files, cpp can include any header file while header files should only include parent class header files and have forward references to the rest. This way cpp file are dependent on each header file not header files to each other. Entire UE4 code is written like that and you don’t see classes returning AActor* because of that isn’t it? AController is still keeps information of controlled APawn and APawn still keep information which AController controls it and oyu got respective functions on each class returning each other.

That said, you still need to check for null pointers either way if your function does not for 100% sure if it return anything.