Download

Is there a way to override PURE_VIRTUAL getter functions?

I want to get the value of range from ShavalaFireGolem.h , calling the function GetRange of ShavalaAI.h.
The editor tells me : error C4716: ‘AShavalaAI::getRange’: must return a value.
What i’m trying to do is:

AShavalaAI *ai = …;
ai->GetRange(); //get 300

ShavalaAI.h

UCLASS()
class SHAVALAPROJECT_API AShavalaAI : public AShavalaPawn , public InterfaceShowPawn{

int32 GetRange();

virtual int32 getRange() PURE_VIRTUAL(AShavalaAI::getRange, ;);

}

ShavalaAI.cpp

int32 AShavalaAI::GetRange()
{
return getRange();
}

ShavalaFireGolem.h

UCLASS()
class SHAVALAPROJECT_API AShavalaFireGolem : public AShavalaAI
{

int32 getRange();

int32 range = 300;
}

ShavalaFireGolem.cpp

int32 AShavalaFireGolem::getRange()
{
return range;
}

Here’s a copy/paste from a working overridden pure virtual:

Parent class pure virtual function:




public:

 /**
 * Get display name of this object.
 */
 virtual FString GetDisplayName() = 0;

Child class implementation:



private:

FString _displayName;

public:

 /**
 * Get display name of this object.
 */
 FORCEINLINE FString GetDisplayName() override
 {
  return _displayName;
 }

So, this is made a little more complicated by the way that Unreal Engine uses C++ than Jocko’s answer suggests.

UE requires that all UObject/UClass types are able to be constructed (so it can create default class objects), therefore they cannot be abstract (i.e. contain true pure virtual functions marked with = 0).
To get round this restriction, UE has the PURE_VIRTUAL macro. This actually provides a body to the function, but makes it an error to ever be executed (it must be overridden in derived classes).

The fix for your issue is to fill in the second parameter of the PURE_VIRTUAL macro, which is the return statement for functions which need a return value:


virtual int32 getRange() PURE_VIRTUAL( AShavalaAI::getRange, return 0; );

FYI, you should also mark the getRange() function in AShavalaFireGolem as virtual and/or override or final.
Also, I’m not sure of your intent with the separate GetRange() function in AShavalaAI, it should be fine to call the virtual getRange() function directly outside of the class.