Download

Abstract methods

Hello forums.

I’ve looking for a way to create abstract methods, or rather methods that MUST be implemented by children inheriting a certain class. As far as I know, all classes should be able to instantiate, so clean abstract methods are not an option. I did some research and found this AnswerHub question with the following answer:

However, this triggers a runtime error followed by a crash.

This is how I implemented the functionality:

Parent



public:
    virtual bool CanConstructHere() { check(0 && "Must be overridden"; return false; )}


Child



public:
    virtual bool CanConstructHere() override;

//.cpp

bool AChild::CanConstructHere()
{
    // Do something

    return true;
}


This triggers the following runtime error:

How exactly can I get this to work?

UE4 has a special macro for implementing pure virtual functions. I’ve only ever seen it used once however.

There’s an example of it here.



virtual void SomeFunction() PURE_VIRTUAL(UMyObject::SomeFunction, );


You cannot instantiate a base class that has pure virtual methods however, so you will only ever be able to use children of this class at runtime.

Pure Virtual reflected functions are not supported IIRC.

If all you want is to stop the crashing, you can remove the check(…) and replace it with:



ensureMsg( false,  TEXT("Please implement this!") );

I would instead rise a blueprint runtime execution error/warning (shows a message on blueprint log panel), but that requires a lot more code which I don’t remember the details right now.

Pure virtual seems to do the trick for me as I will never directly construct the parent, only the children. Thank you.