Search code examples
c++abstract-classunreal-engine5

Unreal engine Abstract class example c++


i have been looking for quite some time online for a good Abstract class (UCLASS(Abstract)) example but haven't came accross a good one yet.

Is there anyone with a good Link i can goto or Anyone who could show me a simple example, i would appreciate alot.

WeaponBase.h

UCLASS(Abstract, Blueprintable)
class FPS_API AWeaponBase : public AActor
{
    GENERATED_BODY()

public:
    // Sets default values for this actor's properties
    AWeaponBase();

    /** This will be used in sub classes */
    UFUNCTION(BlueprintCallable, Category = "Functions")
    virtual void OnFire(AFPSCharacter* Character);
}

Weapon_Assault.h

UCLASS()
class FPS_API AWeapon_Assault : public AWeaponBase
{
    GENERATED_BODY()
    
public:

    FVector spread;

    AWeapon_Assault();

};

Weapon_Assault.cpp

#include "Weapon_Assault.h"

AWeapon_Assault::AWeapon_Assault()
{
    AWeaponBase();
    spread = FVector(0.5f, 0.0f, 100.0f);
}

// this function from abstract super class
void OnFire(AFPSCharacter* Character)
{
}

The original code is quite big so i don't want to post it here, but this is basically what it looks like, and i keep getting errors. Also i can't even declare "OnFire" in main class and subclass at the same time?!


Solution

    1. All class definitions must have ; after last } Like this:
    UCLASS(Abstract)
    class UAnimalBase : public UObject
    {
      GENERATED_BODY()
      public:
        UAnimalBase(const FObjectInitializer& ObjectInitializer);
    };
    
    1. You need to add a declaration of an overridden function to your Weapon_Assault.h
    UCLASS()
    class FPS_API AWeapon_Assault : public AWeaponBase
    {
        GENERATED_BODY()
        
    public:
        FVector Spread;
    
        AWeapon_Assault();
    
        virtual void OnFire(AFPSCharacter* Character) override; // THIS ONE
    
    };
    

    Note that you don't need UFUNCTION() specifier above the overridden function, only on the first declaration.

    1. AWeapon_Assault::AWeapon_Assault() also has a mistake. You don't call constructors of parent classes in C++ they will be called automatically.
    AWeapon_Assault::AWeapon_Assault()
    {
       // AWeaponBase();  THIS LINE IS WRONG
        Spread = FVector(0.5f, 0.0f, 100.0f);
    }
    
    1. Create a definition for your functions in the abstract class (they can stay empty). Yes, it doesn't make sense though it does. Abstract is a specifier only inside of UnrealEngine but code still needs to be compiled with C++ standards. The absence of these definitions will cause compile errors.

    2. We use UpperCamelCase or PascalCase in Unreal Coding Standart which is nice to have. But that one is not necessary. So your variable should be FVector Spread; Also you probably shall wrap it with UPROPERTY() macro but that's a different topic.