Skip to content

Defining a C++ Class

C++ classes must be defined and implemented in separate header (.h) and source files (.cpp). The header file can be placed in either the Public or Private directory of your module, depending on whether the class is meant to be #include-able by other modules or not. The source file, on the other hand, must always be placed in the Private directory.

You can manually create the necessary files, or use the Tools > New C++ Class... wizard in the editor to declare a new class:

Note

The names of the header and source files should match the name of the class, but this is not a strict requirement.

UObjects

Your standard C++ class definitions are perfectly valid in Unreal Engine. However, Unreal Engine extends the capabilities of C++ classes through a generic base class: UObject. Classes that extend UObject, either directly or indirectly, can be registered with the reflection system using the UCLASS macro.

Instances of registered classes are managed by the engine, which means they are automatically serialized, garbage collected, and can be instantiated in the editor. Moreover, any UObject subclass may be used as a base class in Blueprint Classes.

The following sections cover the most important concepts regarding UObjects.

Example

The following is an example of a basic Actor (=AActor) subclass:

MyActor.h
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"

#include "Lamp.generated.h"/* (1)! */

UCLASS(Blueprintable, BlueprintType)
class MODULENAME_API/* (2)! */ ALamp/* (3)! */ : public AActor/* (11)! */ {
    GENERATED_BODY()/* (4)! */

public: 
    ALamp();/* (5)! */

    UFUNCTION(BlueprintCallable, meta=(ToolTip="Toggle the lamp on or off."/* (10)! */))
      void ToggleState();/* (6)! */

    bool IsOn() const { return bIsOn; }/* (7)! */

private:
    UPROPERTY(EditAnywhere, BlueprintReadWrite, meta=(AllowPrivateAccess=true))
      bool bIsOn;/* (8)! */

    UPROPERTY(EditAnywhere, BlueprintReadWrite, meta=(AllowPrivateAccess=true))
      float Brightness;/* (9)! */
};
  1. Contains all the boilerplate code generated by UHT. This file must be included as the last #include in the header file.
  2. The MODULENAME_API macro is akin to the standard extern keyword in C++ and marks the class for external linkage. See External Linkage for more info.
  3. The class name should be in PascalCase and prefixed with one of the recommended prefixes.
  4. Used to inject some boilerplate code generated by UHT into the class body.
  5. UObject subclasses must have a default constructor. The constructor must be light and not perform any heavy operations. See Constructor for more info.
  6. It is a good practice to slightly indent the declaration to clearly highlight its connection with the macro.
  7. You do not have to register everything with the reflection system, only the things you want to expose to the editor or Blueprints.
  8. It is a good practice to slightly indent the declaration to clearly highlight its connection with the macro.
  9. It is a good practice to slightly indent the declaration to clearly highlight its connection with the macro.
  10. Assigned values that contain spaces must be enclosed in quotes.
  11. AActor is one of the most commonly extended subclasses of UObject with a lot of built-in functionality. The concepts discussed here, however, are limited to UObjects. See the API Reference for more info on AActors.

In the above example, the highlighted lines are specialized macros that register the UObject subclass and its member variables (properties) and functions with the reflection system. These macros accept specifiers and meta specifiers that alter their behavior and metadata. Specifiers and meta specifiers are case-insensitive, but by convention, they are often written in PascalCase like everything else in Unreal Engine.

The following sections cover the most commonly used specifiers and meta specifiers. For an exhaustive list of available options, see here.

UCLASS

The UCLASS macro registers the class with the reflection system, allowing you to instantiate the class in the editor and extend it with Blueprints. It can accept several specifiers that dictate how the class shows up in the editor.

Specifiers

UCLASS accepts the following specifiers:

UCLASS(Abstract)

When present, the class cannot be instantiated directly. Subclasses must be created instead.

UCLASS(Blueprintable / NotBlueprintable)

Exposes this class as an acceptable base class for creating Blueprints. See Blueprint Classes for more info.

Subclasses will inherit this property, unless explicitly marked as NotBlueprintable.

UCLASS(BlueprintType / NotBlueprintType)

Exposes this class as a type that can be used for variables in Blueprints. See Blueprint Variables for more info.

Subclasses will inherit this property, unless explicitly marked as NotBlueprintType.

UCLASS(Config="FileName" / DefaultConfig)

Indicates that this class is allowed to store data in a configuration file (.ini). Any member variable preceded by UPROPERTY(Config) or UPROPERTY(GlobalConfig) will be loaded from the file. See Config Files for more info.

Subclasses will inherit this property, but they can change the config file by re-declaring the Config specifier.

UCLASS(EditInlineNew / NotEditInlineNew)

When combined with a UPROPERTY(Instanced) reference, or UCLASS(DefaultToInstanced), allows you to create a new instance of this class directly from the Details panel. This is particularly useful when the class is meant to be set via Class Defaults:

UCLASS(EditInlineNew

Without this specifier, a reference to a UObject subclass can only be set to an existing instance of the class, which works well for references that are meant to be set in the Level Editor:

UCLASS(NotEditInlineNew)

UCLASS(MinimalAPI)

Indicates that only the class's type information to be exported. See External Linkage for more info.

UCLASS(Transient / NonTransient)

Indicates that objects of this type should not be serialized and saved to disk.

This specifier is commonly associated with classes that are not to be persisted between sessions, but instead are created and destroyed within a single game session. A good example of transient objects are Player Controller instances, which are created when a player joins a level and are destroyed when the player leaves.

Subclasses will inherit this property, unless explicitly marked as NonTransient.

Meta Specifiers

UCLASS accepts the following meta specifiers:

UCLASS(meta=(BlueprintSpawnableComponent))

Indicates that this class can be spawned as a component in a Blueprint classes via the Add button.

UCLASS(meta=(DisplayName="Some Alternative Name"))

Specifies an alternate name for the class to be displayed in the editor. UE will use the class's name otherwise.

UCLASS(meta=(DisplayThumbnail=true))

Specifies whether the class should have a thumbnail image displayed in the editor or not.

UCLASS(ToolTip="Some description" & ShortToolTip="Some short description")

Used to provide a description of the class that will be displayed in the editor when the class is hovered over. UE will attempt to use the docstring of the class if this specifier is not present.

UCLASS(meta=(BlueprintThreadSafe))

Indicates that the methods of this class are thread-safe and can be called from non-game threads. You can exclude specific methods from this specifier.

External Linkage

The MODULENAME_API macro is akin to the standard extern keyword in C++ and marks the class for external linkage. This means that other modules can instantiate and interact with the class. Alternatively, rather than applying the macro to the class, you can apply it to individual functions to mark them for external linkage only.

UCLASS()
class UMyClass : public UObject {
    GENERATED_BODY()
public:
    MODULENAME_API void MyFunction();
};

Another option is to omit this macro entirely and use the UCLASS(MinimalAPI) specifier. This would tell the engine that only the class's type information is to be exported (for casting, etc.). Reducing the amount of exported information can help reduce compile times.

UPROPERTY

Registering a member variable with the reflection system allows you to read and write the value in the editor and Blueprints. The macro accepts a number of specifiers and meta specifiers that dictate how the property can be accessed and modified.

The UPROPERTY macro also allows the garbage collector to trace the object, preventing it from being prematurely destroyed. This is particularly important for member variables that are also UObject subclasses. Without the macro, object would be destroyed shortly after construction, leading to a crash when the object is accessed. See Subobjects for an example.

Specifiers

UPROPERTY accepts the following specifiers:

UPROPERTY(EditAnywhere / EditDefaultsOnly / EditInstanceOnly /
VisibleAnywhere / VisibleDefaultsOnly / VisibleInstanceOnly)

Mutually exclusive controls for how the property shows up in the editor. The Edit specifiers allow the property to be modified in the editor, while the Visible specifiers only allow the property to be viewed.

There are two primary places for properties to be edited / visible in the editor:

  • The Details Panel in the Level Editor: This is referred to as Instance in the specifiers.

    The Details Panel in the Level Editor

  • The Details Panel in the Blueprint Editor: This is referred to as Defaults in the specifiers.

    The Details Panel in the Blueprint Editor

UPROPERTY(BlueprintReadWrite / BlueprintReadOnly)

Specifies whether the property is read-only or read-write in Blueprint subclasses.

Properties can marked as BlueprintReadWrite even if they are protected or private. Note that in such cases, you also need to set the UPROPERTY(meta=(AllowPrivateAccess=true)) meta specifier.

UPROPERTY(BlueprintGetter=GetFunctionName & BlueprintSetter=SetFunctionName)

Specify dedicated getter and setter functions for the property in Blueprint subclasses.

UPROPERTY(BlueprintReadWrite, BlueprintGetter=GetAcceleration, BlueprintSetter=SetAcceleration)
  float Acceleration = 0;

UFUNCTION()// (1)!
  float GetAcceleration() const;

UFUNCTION()
  void SetAcceleration(float InAcceleration);
  1. See Functions to learn more about UFUNCTION()s.

UPROPERTY(Category="Category Name")

Specifies the category in which the property will be displayed in the Details panel.

Categories can be nested by separating them with a pipe (|) without spaces, e.g., Main Category|Subcategory.

UPROPERTY(Config / GlobalConfig)

Indicates that this property should be loaded from a configuration file (.ini) after construction. Config properties can be overridden later but GlobalConfigs are read-only.

See Config Files for more info.

UPROPERTY(Instanced)

Indicates that instances of the class will have their own unique copy of the default value assigned to this property.

UPROPERTY(Interp)

Exposes the property to the Sequencer for keyframe interpolation. See Cinematics for more info.

UPROPERTY(NonTransactional)

Indicates that changes to this property's value will not be included in the editor's Undo / Redo history.

UPROPERTY(Replicated / NotReplicated)

Marks the property for replication. Note that using this specifier alone is not enough for this property to replicate in multiplayer games. See Replication for more info.

Subclasses will inherit this property, unless explicitly marked as NotReplicated.

UPROPERTY(ReplicatedUsing=FunctionName)

Specifies a function that will be called when the property is replicated. See Replication for more info.

UPROPERTY(SaveGame)

Indicates that this property should be included when the object is serialized to an FArchive with ArIsSaveGame set. See Game Saves for more info.

UPROPERTY(Transient)

Indicates that objects of this type should not be serialized and saved to disk.

Meta Specifiers

UPROPERTY accepts the following meta specifiers:

UPROPERTY(meta=(ConsoleVariable="SomeName"))

Exposes the property as a Console Variable. See Console for more info.

UPROPERTY(meta=(DisplayName="Some Name"))

Specifies an alternate name for the property to be displayed in the editor. UE will use the property's name otherwise.

UPROPERTY(meta=(DisplayPriority=123))

Sets the priority of the property in the Details panel. Properties are displayed in ascending order of priority.

UPROPERTY(meta=(DisplayThumbnail=true))

Specifies whether the property should have a thumbnail image displayed in the editor or not.

UPROPERTY(meta=(EditCondition="Expression"))

Specifies a boolean expression that must be true for the property to be editable in the editor. The property is read-only when the expression evaluates to false.

With UPROPERTY(meta=(EditConditionHides)) the property is hidden when the expression is false.

UPROPERTY(meta=(ShowOnlyInnerProperties))

When applied to a USturct property, the Details panel will list out the inner properties of the struct:

Show Only Inner Properties

By default, you would have to expand a struct property to see its inner properties.

UPROPERTY(EditAnywhere, Category="Without ShowOnlyInnerProperties")
  FSomeStruct SomeStruct;

UPROPERTY(EditAnywhere, Category="With ShowOnlyInnerProperties", meta=(ShowOnlyInnerProperties))
  FSomeStruct AnotherInstanceOfSomeStruct;

UPROPERTY(meta=(ToolTip="Some description"))

Used to provide a description of the property that will be displayed in the editor when the property is hovered over. UE will attempt to use the docstring of the property if this specifier is not present.

UFUNCTION

Registering a member function with the reflection system via the UFUNCTION macro will expose the function to the editor and the engine, allowing it to be called and overridden in Blueprints.

Arguments of such functions may be decorated with the UPARAM macro. This macro has a very limited functionality. The most common use of this macro is to mark passed-by-reference arguments as input arguments. By default, Unreal Engine would interpret any argument that is passed by reference as an auxiliary function output. By placing UPARAM(ref) prior to the declaration of the argument, you can mark it as an input argument.

MyClass.h
UFUNCTION(BlueprintCallable)
  float/* (1)! */ AnotherFunction(
    float PassedByValueInput, 
    UPARAM(ref) FSomeStruct& PassedByRefInput, 
    FSomeStruct& PassedByRefOutput
  );
  1. You can still have a conventional return value for your function. This is quite useful for returning error codes or other status information.

Specifiers

UFUNCTION accepts the following specifiers:

UFUNCTION(BlueprintCallable)

Exposes this function to Blueprint classes.

UFUNCTION(BlueprintCallable)

UFUNCTION(BlueprintPure)

Marks the function as a Pure Function. Pure functions will show up as a node with no execution pins. Pure functions do not cache their return values and are re-evaluated every time their output is invoked.

UFUNCTION(BlueprintPure)

This is the default behavior for any const functions in the class. In order to exclude a const function from this behavior, you need to use the UFUNCTION(BlueprintPure=false) specifier.

UFUNCTION(CallInEditor)

Binds the function to a button in the editor. The function cannot have any parameters or return values. They will be alphabetically ordered.

UFUNCTION(CallInEditor)

UFUNCTION(Exec)

Exposes the functrion as a Console Command. See Console for more info.

UFUNCTION(BlueprintAuthorityOnly / BlueprintCosmetic)

Indicates that the function can only be called on machines with authority or that it is purely cosmetic and can should only be executed on the client. See Replication for more info.

UFUNCTION(Client / Server)

Marks the function is either a Client or Server RPC. See Replication for more info.

UFUNCTION(Reliable / Unreliable)

Indicates whether the function should be replicated via reliable or unreliable channels. See Replication for more info.

UFUNCTION(WithValidation)

Indicates that the function has a corresponding validation function, with the exact same parameters but a boolean return value.

MyClass.h
UFUNCTION(Server, WithValidation)
  void SomeFunction(float InValue);
MyClass.cpp
bool UMyClass::SomeFunction_Validate(float InValue) { ... };

This feauture is particularly useful for RPC functions, because the validation function, which should be named FunctionName_Validate, is called on the server before the function is executed and should return true if the function should be executed.

Events

In order to declare a function that can be overridden in Blueprint subclasses, you need to use one of the following specifiers:

UFUNCTION(BlueprintNativeEvent)

Indicates that the function can be overridden in Blueprint subclasses. If it is not overridden, the C++ implementation will be called. This specifier cannot be applied to a function with a return value.

MyEventfulActor.h
UFUNCTION(BlueprintNativeEvent)
  void Damaged(float Damage, UPARAM(ref) FHitInfo& HitInfo);

The C++ implementation of the function is defined under the same name but suffixed with _Implementation:

MyEventfulActor.cpp
void AMyEventfulActor::Damaged_Implementation(float Damage, /*(1)!*/FHitInfo& HitInfo) { ... }
  1. Note that we don't have to repeat UPARAM(ref) here. The engine knows that this is an input, based on the declaration in the header file.

The declared function will show up as an event in the Event Graph of any Blueprint that extends the class:

UFUNCTION(BlueprintNativeEvent) without Output Parameters

While the function cannot have a return value, it can have outputs via passed-by-reference arguments. For example:

UFUNCTION(BlueprintNativeEvent, meta=(ToolTip="A native event with an output parameter"))
  void Fallen(ESurfaceType SurfaceType, float& InflictedDamage);

In such cases, however, the function will not show up as an event, but as an overridable function:

UFUNCTION(BlueprintNativeEvent) with an Output Parameter

UFUNCTION(BlueprintImplementableEvent)

This specifer is just like UFUNCTION(BlueprintNativeEvent), but it no longer requires a C++ implementation. If the function is not overridden in a Blueprint subclass, it is simply ignored.

Implementable events can be forced to show up as overridable functions in Blueprints even if they have no output arguments. You can do this by using the UFUNCTION(meta=(ForceAsFunction)) meta specifier.

There is another specifier for events that can be used in conjunction with the above specifiers:

UFUNCTION(SealedEvent)

Prevents the event from being overridden in Blueprint subclasses. This is equivalent to the final keyword in C++.

Meta Specifiers

UFUNCTION accepts the following meta specifiers:

UFUNCTION(meta=(BlueprintAutocast))

Marks the function as a casting function, which will be automatically invoked when the data types match the function's parameter and return value. Note that the function needs to be UFUNCTION(BlueprintPure) and static.

UFUNCTION(BlueprintPure, meta=(BlueprintAutocast))
  static ESurfaceType IntToSurfaceType(int32 InInt);

UFUNCTION(BlueprintPure)`

UFUNCTION(meta=(BlueprintProtected))

Equivalent to the protected keyword in C++. The function can't be invoked outside of the class or its subclasses.

UFUNCTION(meta=(CompactNodeTitle="X"))

Specifies a compact representation for the function. This is widely used for mathematical functions.

UFUNCTION(BlueprintPure, DisplayName="Boolean XoR", meta=(CompactNodeTitle="⊕"))
  static bool XoR(bool A, bool B);

UFUNCTION(meta=(CompactNodeTitle="X"))

UFUNCTION(meta=(DisplayName="Some Name"))

Specifies an alternate name for the function to be displayed in the editor. UE will use the function's name otherwise.

UFUNCTION(meta=(ExpandEnumAsExecs="EnumTypeName" / ExpandBoolAsExecs="BoolVarName"))

Expands the function's return value (either an enum or a bool) into execution pins. This is quite useful for flow control functions.

UFUNCTION(BlueprintCallable, meta=(ExpandBoolAsExecs="ReturnValue"/* (1)! */))
  bool HealthBelowZero();
  1. Instead of "ReturnValue", you can name a passed-by-reference bool parameter to be used instead.

UFUNCTION(meta=(ExpandBoolAsExecs))

UFUNCTION(meta=(Latent, LatentInfo="VariableName"))

Marks the function as a latent action. Latent functions can suspend their execution and resume it later. There are several builtin latent functions in Unreal Engine, such as Delay, Move Component To, etc.

Latent functions need to accept a passed-by-value FLatentActionInfo parameter named "VariableName".

Incomplete

This section is incomplete and needs to be expanded.

UFUNCTION(meta=(NotBlueprintThreadSafe))

Excludes the method as a non-thread-safe function in a class marked as UCLASS(meta=(BlueprintThreadSafe)).

UFUNCTION(meta=(ParameterName=DefaultValue))

Specifies (or overrides) the default value for the named parameter in the Blueprint editor.

UFUNCTION(meta=(ReturnDisplayName="Some Name"))

Specifies an alternate name for the function's return value, instead of the default "ReturnValue".

UFUNCTION(ToolTip="Some description" & ShortToolTip="Some short description")

Used to provide a description of the function that will be displayed in the editor when the function is hovered over. UE will attempt to use the docstring of the class if this specifier is not present.

Inline Functions

Another macro commonly used with member functions is FORCEINLINE. This macro is replaced with the right keyword for the compiler to inline the function. This is particularly useful for small functions that are called frequently.

FORCEINLINE UArrowComponent * GetSpawnPoint() { return OpenFirePoint; }

Constructor

UObjects must have a default constructor, which should be lightweight and focused solely on initializing the object's properties and their respective attributes. Any more complex or resource-intensive initialization should be deferred to the appropriate lifecycle hooks.

Subobjects

Properties that reference UObject subclasses are referred to as subobjects. These properties (which must be preceded by the UPROPERTY macro) cannot be initialized via the standard new keyword. Instead, you need to use the CreateDefaultSubobject method. This method is an overloaded template function that in its simplest form looks like this:

template<class TObjectType/* (1)! */>
TReturnType* CreateDefaultSubobject(FName SubobjectName/* (2)! */) { ... }
  1. The type of the object that you want to create. You do not need to include an asterisk (*) to indicate a pointer type.
  2. A unique name for the subobject, which can be the same as the property name or something entirely different.

When invoked, the function will create a new instance of the specified class (on the heap) and return a pointer to it. If the function fails to create the subobject, it will return nullptr.

Another variant of the function allows you to specify an alternative type for the return value. This is particularly useful for polymorphic classes and allows you to cast the return value to a parent class of the subobject:

template<class TReturnType, class TObjectType>
TReturnType* CreateDefaultSubobject(FName SubobjectName) { ... }

The following is an example of this method in action:

MyActor.h
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MyActor.generated.h"

UCLASS()
class MODULENAME_API AMyActor : public AActor/* (1)! */ {
    GENERATED_BODY()

public: 
    AMyActor();

private:
    UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta=(AllowPrivateAccess=true))
      TObjectPtr/* (2)! */<UStaticMeshComponent/* (3)! */> MeshComp;
};
  1. In this example, we are extending the AActor class, one of the most extensively used subclasses of UObject.
  2. TObjectPtr is a special pointer wrapper that is used to reference UObjects. See Pointers for more info.
  3. UStaticMeshComponent is a subclass of USceneComponent, which is derived from UObject. Therefore, this property is considered a subobject.
MyActor.cpp
#include "MyActor.h"

AMyActor::AMyActor() {
    MeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("AltMeshComp"));
    if (MeshComp) {
        ...  // We can initialize the attributes of the mesh component.
    }
}

Finally, there is a third variant of the function with a different name but the same signature: CreateOptionalDefaultSubobject. Subojects created with this function can be overridden by subclasses, which is not possible with the standard method. Though using this method alone is not sufficient.

To allow subclasses to override subobjects, you need to declare an alternative default constructor for your base class and your subclass that accepts an FObjectInitializer reference:

MySubActor.h
UCLASS()
class MODULENAME_API AMySubActor : public AMyActor {
    GENERATED_BODY()

public:
    AMySubActor(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
};

Your subclass's constructor should then call the DoNotCreateDefaultSubobject method on the passed ObjectInitializer:

MyActor.cpp
AMySubActor::AMySubActor(const FObjectInitializer& ObjectInitializer)
    : Super(ObjectInitializer.DoNotCreateDefaultSubobject(TEXT("AltMeshComp"))) { ... }

Another useful method on FObjectInitializers is SetDefaultSubobjectClass which allows you to specify a different class for a subobject defined in a parent:

AMySubActor::AMySubActor(const FObjectInitializer& ObjectInitializer)
    : Super(ObjectInitializer.SetDefaultSubobjectClass<UCustomStaticMeshComponent>(TEXT("AltMeshComp"))) { ... }

Instantiation

To instantiate a new instance of a UObject subclass outside a parent object's constructor, you need to use the NewObject template function. The function accepts several arguments:

template<class T>
T* NewObject(UObject* Outer/* (1)! */, UClass* Class/* (2)! */, FName Name = NAME_None/* (3)! */, ..)
  1. The outer object that will own the new object. This is typically the object that is responsible for the new object's creation and destruction. If omitted, the new object will be garbage collected when it goes out of scope.
  2. The class of the new object. This is an optional argument, as the function can infer the class from the return type. You can use this argument for polymorphic classes.
  3. A unique name for the new object. If not provided, NewObject will generate a unique name for the object.

Life Cycle Hooks

Incomplete

This section is incomplete and needs to be expanded.

Reflection and Type Info

During runtime, any class registered with the UCLASS macro will have an associated UClass object, containing information about the class, its properties and functions, and other metadata. The object is accessible via the GetClass() method on any instance of a UObject subclass.

The associated UClass object maintains an instance of the class that is referred to as the Class Default Object. The CDO is essentially a template object, generated by the class constructor (hence, the need for a default constructor) and unmodified thereafter.

Serialization

The reflection system enables the engine to automatically serialize and deserialize objects to and from permanent storage. Network replication, game saves, and many other features rely on this.

The mechanism is enabled by the Serialize method, which accepts an FArchive reference as an argument, and reads / writes a delta of the object and its CDO when invoked. You can override this method to provide custom serialization logic.

bool AMyActor::Serialize(FArchive& Ar) {
    Ar << bIsOn;
    Ar << Brightness;
    return true; /* (1)! */
}
  1. The method should return true if the serialization was successful. If it returns false, UE will attempt to serialize the object again, this time using the default method.

There is also a NetSerialize method that is used for network replication. You could override this method for an alternative serialization logic that is more network-friendly.

Incomplete

This section is incomplete and needs to be expanded.

Pointers

Member variables that point to an instance of a UObject subclass, aka subobjects, must be declared with a pointer wrapper. Pointer wrappers can inform the engine about the object's life cycle, and how it should be garbage collected. For more info on pointer wrappers, see Object Pointers.

Thanks to the reflection system, you can also pass around pointers to classes rather than objects. Such pointers can be used to instantiate new objects of the class, or to cast an arbitrary object to a specific class. See Class Pointers for more info.

Casting

Unreal provides an alternative to the standard C++ dynamic cast: Cast<T>. The function is faster and more reliable than the standard cast, and it can cast a pointer to another class up and down the inheritance hierarchy, which is particularly useful for polymorphic classes.

AWeapon* Weapon = Cast<AWeapon/* (1)! */>(Shotgun);
if (Weapon/* (2)! */) {
    ... // Do something with the weapon.
}
  1. You can either pass the class name directly or a pointer to the associated UClass object.
  2. The function will return nullptr if the cast fails. A simple boolean check is sufficient to determine if the cast was successful.

Typedefs

The UObject class defines a couple of useful typedefs that will come in handy when working with the engine's API:

  • ThisClass is a typedef for the class itself. This is particularly useful when you need to a function pointer to one of the class's member functions:

    void AMyEventfulActor::BindToScoreChanged() {
        OnScoreChangedDelegate/* (1)! */.BindUObject(this, &ThisClass::OnScoreChanged);
    }
    
    1. See Delegates for more info.
  • Super is a typedef for the class's parent class. This shortcut is often used to call the parent's functions in overridden methods:

    void AMyEventfulActor::CheckForImpact() {
        Super::CheckForImpact();
        ... // and then do something else.
    }