I created a class through the C++ class wizard in unreal engine that extends UInterface. All I’m trying to do is add a single function to the public section of “I” prefixed class. According to the unreal engine documentation, an implementation should be optional:
If I just leave the function unimplemented, building fails with unresolved external symbol. If I provide a default for the function implementation, it succeeds.
I thought maybe this was because there needs to be an implementation somewhere, but even if I try to have a class inherit the interface and provide an implementation it creates more unresolved external symbol issues.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "CombatCharacterInterface.generated.h"
UINTERFACE(MinimalAPI)
class UCombatCharacterInterface : public UInterface
{
GENERATED_BODY()
};
class RPGSHOOTER_API ICombatCharacterInterface
{
GENERATED_BODY()
public:
virtual bool TestFunction();
};
CombatCharacterInterface.gen.cpp.obj : error LNK2001: unresolved external symbol “public: virtual bool __cdecl ICombatCharacterInterface::TestFunction(void)” (?TestFunction@ICombatCharacterInterface@@UEAA_NXZ)
2>CombatCharacterInterface.cpp.obj : error LNK2001: unresolved external symbol “public: virtual bool __cdecl ICombatCharacterInterface::TestFunction(void)” (?TestFunction@ICombatCharacterInterface@@UEAA_NXZ)
Because you’ve promised that ICombatCharacterInterface has the function TestFunction, but haven’t actually provided it anywhere. Since the compiler don’t know where the definition might live, the linker has to check that and fail if it doesn’t find it.
You have a couple of options for solutions.
First would be the pure C++ solution and add an “= 0” at the end: TestFunction() = 0;
. This would identify it as a “pure virtual” function that needs no implementation from this class. If you try to create an instance of a function with a pure virtual the compiler will generate an error. Unreal doesn’t really like pure virtual functions all the time so this can cause you other problems depending on how you’re implementing the interface.
The Unreal solution would be to use the PURE_VIRTUAL
macro after the function: TestFunction() PURE_VIRTUAL( TestFunction, return false; )
. That macro creates a function body with a bit of code that will always fail when run. So you don’t get a compiler error anymore if you try to make one but if you call it on an instance that didn’t implement it you’ll hit the fatal error built into the macro.
Or you can give it an implementation.
In any case, if you’re relying on only virtual functions you should be careful and consider using the CannotImplementInterfaceInBlueprint meta in the UINTERFACE macro. Otherwise blueprint could claim to implement your interface without actually being able to implement it.