How to do implicit casting of interfaces in C++?

There is a wonderful thing that can be done with Blueprints and I don’t know how to do it in C++.

That is the implicit casting of interfaces with polymorphism. Something just great.

This is an example of what I’m talking about.

I implemented the interface in a class derived from HUD. However I can use the interface directly using a reference to the parent class without casting.

This is great!!

However I can’t find a way to do the same in C++. (Obviously without using casting… I know if it’s cast I can do it).

So I looked in the documentation and I didn’t see anything about it.

What is the trick then?
Can i do the same with Unreal C++ or is it something that is only available for bluprints?

Thank you so much!!

You can’t. The “Casting” is still happening, it’s just hidden from you in Blueprint because it’s more convenient for nodes.

2 Likes

Here’s an attempt :

#define TryExecuteInterface(InterfaceName, FuncName, Target, ...) if (Target && Target->Implements<U##InterfaceName>()) { I##InterfaceName::Execute_##FuncName(Target, __VA_ARGS__); }

//usage
TryExecuteInterface(GamePlayHUDInterface, ShowScore, PC->GetHUD(), Score);

This obviously won’t work if you need return values from interface calls. But since the call is conditional, not sure what kind of return value you’d expect when it’s not called anyways.

1 Like

Just keep in mind there is NO “implicit” cast happening in anycase.

1 Like

Thank you very much for your reply

Thank you very much for your answer and for your example.