# Class

## Creating a 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 a 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. See [Architecture](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/build-system#architecture) to learn more.

You can manually create the necessary files, or navigate to **Tools** 🡒 **New C++ Class...** in the editor to declare a new class by specifying its name, module, and desired path:

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDb1evVoYDUh1tShfU1sg%2Fuploads%2FlnKbnbXSiYQKrPm5SgkX%2Fadd-cplusplus-class-noaudio-resized.mp4?alt=media&token=ba851168-b995-4504-bec7-111237a436f0>" %}

## `UObject` Subclasses

Standard C++ class definitions are perfectly valid in Unreal Engine and can be used without restriction. However, Unreal extends the capabilities of regular classes through a generic base class: `UObject`. Subclasses of `UObject` (direct or indirect) can be registered with Unreal's **Reflection System**, allowing for automatic garbage collection, serialization, and Blueprint integration. Many of Unreal’s core types—including [`AActor`](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) and [`UActorComponent`](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference)—are built on top of `UObject`.&#x20;

To mark a `UObject` subclass for reflection, the declaration must be preceded by the [`UCLASS()`](#the-uclass-macro) macro. The macro will be identified by the [UHT](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/..#reflection-system) which will generate the necessary boilerplate to integrate the class into the engine's reflection system. The properties and methods of the class will also need to be individually marked for reflection using the [`UPROPERTY()`](#the-uproperty-macro) and the [`UFUNCTION()`](#the-ufunction-macro) macro, respectively, if needed.

The following is an example of defining a `UObject` subclass.

<pre class="language-cpp" data-title="Lamp.h"><code class="lang-cpp">#pragma once

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

#include "Lamp<a data-footnote-ref href="#user-content-fn-1">.generated.h</a>"

UCLASS(<a data-footnote-ref href="#user-content-fn-2">Blueprintable</a>, <a data-footnote-ref href="#user-content-fn-2">BlueprintType</a>)
class <a data-footnote-ref href="#user-content-fn-3">MODULENAME_API</a> <a data-footnote-ref href="#user-content-fn-4">ALamp</a> : public AActor {
    <a data-footnote-ref href="#user-content-fn-5">GENERATED_BODY()</a>

public:
    ALamp();
      
    UFUNCTION(<a data-footnote-ref href="#user-content-fn-6">BlueprintCallable</a>, meta=(<a data-footnote-ref href="#user-content-fn-7">DisplayName</a>="UpdateState"), <a data-footnote-ref href="#user-content-fn-7">ToolTip</a>="Update the state of the lamp.")
    void SetState(bool bInState);
    
private:
    UPROPERTY(<a data-footnote-ref href="#user-content-fn-8">EditAnywhere</a>, <a data-footnote-ref href="#user-content-fn-8">BlueprintReadWrite</a>, meta=(<a data-footnote-ref href="#user-content-fn-9">AllowPrivateAccess=true</a>))
    bool bState;
};
</code></pre>

Instances of this class will now possess a `GetClass()` method that returns a pointer to a [`UClass`](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) object, containing type information, and allowing for querying and interacting with the class's methods and properties. There is also a static method, `StaticClass()`, which can retrieve the corresponding `UClass` instance directly, allowing access to type information without requiring an instance of the class. See the [**API Reference**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) to learn more.

Because every reflected class corresponds to a `UClass` object, you can refer to classes themselves as first-class values using `UClass*` pointers. These **class pointers** enable dynamic behaviors such as spawning actors of a type chosen at runtime, creating class-based dropdowns in the editor, or implementing factory patterns without hard-coding class names. In many ways, `UClass*` serves as a dynamic handle to a type, unlocking a wide range of systems. See [**Class Pointers**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) to learn more.

`UObject` subclasses ***must*** have a default constructor. This is because the `UClass` instance will want to hold a **Class Default Object** (CDO)—a template created at startup by calling the class’s default constructor. Whenever a new object is spawned, Unreal clones the CDO’s state to initialize it.&#x20;

Due to this design constraint, the constructor will need to be as bare-bones as possible—only initializing the class' properties and not much else. More complicated initialization processes must be done through appropriate [life cycle hooks](#life-cycle-hooks). It should also be deterministic: serialization in Unreal works by saving only the *delta* with the CDO, so any randomness or side effects in the constructor can lead to inconsistent or broken behavior.

Finally, it should be noted that `UObject` instantiation is not done through regular C++ `new` allocation. Instead, UObject-derived instances are created using the engine-specific function,**`NewObject`**, or within a parent object’s constructor, in which case they will be referred to as **subobjects**. See [Instantiation](#instantiation) to learn more.

### The `UCLASS` Macro

The `UCLASS()` macro accepts a set of **specifiers** and **meta specifiers** that alter how the class is exposed to the engine and the editor.

#### Specifiers

{% hint style="info" %}

## `UCLASS(Abstract)`

When present, the class is considered to be an abstract base class and cannot be instantiated directly.&#x20;
{% endhint %}

{% hint style="info" %}

## `UCLASS(Blueprintable)`

When present, the class can be selected as a **parent** for a [**Blueprint Class**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/blueprint/constructs/class).&#x20;

Subclasses will inherit this property, unless they are explicitly marked with `UCLASS(NotBlueprintable)`.&#x20;
{% endhint %}

{% hint style="info" %}

## `UCLASS(BlueprintType)`

When present, the class can be selected as the object type for a variable in a [**Blueprint Class**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/blueprint/constructs/class).

Subclasses will inherit this property, unless they are explicitly marked with `UCLASS(NotBlueprintType)`.
{% endhint %}

{% hint style="info" %}

## `UCLASS(Config="FileName")`

When present, the engine will attempt to read the value of any property with the `UPROPERTY(Config)` specifier from a **config file**. You can use this in conjuntion with `UCLASS(DefaultConfig)` to ensure that only the **default** `.ini` files are used. See [**Config Files**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) to learn more.

Subclasses will inherit this specifier, but they can re-declare it to override the file name.
{% endhint %}

{% hint style="info" %}

## `UCLASS(EditInlineNew)`

When present, an object reference to this class with the **`UPROPERTY(Instanced)`** specifier will allow you to create a new instance of this class directly from the **Details** panel, rather than having to select an existing instance. This is particularly common when the instance is meant to be configured as **Class Defaults**:

<p align="center"><img src="https://413042066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDb1evVoYDUh1tShfU1sg%2Fuploads%2FSq28YLTyl1Nnn6g4Z1bA%2Fimage.png?alt=media&#x26;token=7dde43f9-60cb-4d1c-ac8e-2a75ec42a5ef" alt="" data-size="original"></p>

Alternatively, you can use the **`UCLASS(DefaultToInstanced)`** specifier to force this behavior globally.
{% endhint %}

{% hint style="info" %}

## `UCLASS(MinimalAPI)`

Indicates that only the class's type information to be *exported*. See [**External Linkage**](#external-linkage) to learn more.
{% endhint %}

{% hint style="info" %}

## `UCLASS(Transient)`

Indicates that objects of this type are **transient**.&#x20;

Transient objects are not saved to disk or loaded from it.&#x20;

Subclasses will inherit this property, unless they are explicitly marked with `UCLASS(NonTransient)`.

It is more common to mark individual properties as transient, using the `UPROPERTY(Transient)` macro.
{% endhint %}

#### Meta Specifiers

{% hint style="info" %}

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

Specifies an alternate name for the class to be displayed in the editor.
{% endhint %}

{% hint style="info" %}

## `UCLASS(meta=(DisplayThumbnail=true))`

Specifies whether the class should have a thumbnail image displayed in the editor or not.
{% endhint %}

{% hint style="info" %}

## `UCLASS(meta=(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.
{% endhint %}

{% hint style="info" %}

## `UCLASS(meta=(BlueprintSpawnableComponent))`

Indicates that this class can be spawned as a component in a [**Blueprint Class**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/blueprint/constructs/class) via the **Add** button.

This is only relevant for [**Actor**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) subclasses.
{% endhint %}

{% hint style="info" %}

## `UCLASS(meta=(BlueprintThreadSafe))`

Indicates that the functions in the class are multi-thread safe.&#x20;

This is only relevant for [**Blueprint Function Library**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) subclasses.
{% endhint %}

### The `UPROPERTY` Macro

The `UPROPERTY()` macro is used to mark properties that the engine and the editor must be aware of. This includes properties that:

* Must be **visible** or **editable** in the editor or [**Blueprints**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/blueprint/constructs/class).
* Must be **serialized** for saving to/loading from disk and [**replication**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference).
* Point to other `UObject`s, which we want the garbage collector to know about.
* May need to be queried via the `FindField()` method on the corresponding `UClass` instance.

The `UPROPERTY()` macro accepts a set of **specifiers** and **meta specifiers** that alter how the engine and the editor work with the property.

#### Specifiers

{% hint style="info" %}

## `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.

`Defaults` limits the property's editability/visibility to the **Class Defaults** panel in a [**Blueprint Class**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/blueprint/constructs/class)**:**

<p align="center"><img src="https://413042066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDb1evVoYDUh1tShfU1sg%2Fuploads%2FAJ5rcjIRmE9OpHKKc82M%2Fimage.png?alt=media&#x26;token=fb86995f-7537-4d48-95c4-e28c03e1327a" alt=""></p>

`Instance`, on the other hand, means the property will be shown in association to an instance, e.g., a placed instance in a level:

<p align="center"><img src="https://413042066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDb1evVoYDUh1tShfU1sg%2Fuploads%2Fktobe9Zn5EzJipr21w3R%2Fimage.png?alt=media&#x26;token=8f311d6b-33fc-4907-a3b2-8ec584db502e" alt=""></p>

`Anywhere` will show up the property in both **Class Defaults** and individual instances.
{% endhint %}

{% hint style="info" %}

## `UPROPERTY(BlueprintReadWrite` / `BlueprintReadOnly)`

When present, the variable can be accessed when scripting in [**Blueprints**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/blueprint/constructs/class).

Properties can take on either of these specifiers even if they are **protected** or **private**. Note that in such cases, you also need to set the **`UPROPERTY(meta=(AllowPrivateAccess=true))`** meta specifier.
{% endhint %}

{% hint style="info" %}

## `UPROPERTY(BlueprintGetter=GetFunctionName` & `BlueprintSetter=SetFunctionName)`

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

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

UFUNCTION()
float GetAcceleration() const;

UFUNCTION()
void SetAcceleration(float InAcceleration);
```

{% endhint %}

{% hint style="info" %}

## `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 character (`|`) without any spaces around it, e.g., `Main Category|Subcategory`.
{% endhint %}

{% hint style="info" %}

## `UPROPERTY(Config)`

When present, the engine will attempt to read the value of any property from a **config file**. For this to work, the class will need to have the `UCLASS(Config)` specifier. See [**Config Files**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) to learn more.
{% endhint %}

{% hint style="info" %}

## `UPROPERTY(Instanced)`

Indicates that instances of the class will have their own unique copy of the default value assigned to this property. Otherwise, except in the case of subobjects (with the **`UCLASS(DefaultToInstanced)`** specifier), default values will share memory.
{% endhint %}

{% hint style="info" %}

## `UPROPERTY(Interp)`

Exposes the property to the **Sequencer** for keyframe interpolation. See [**Sequencer**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) for more info.
{% endhint %}

{% hint style="info" %}

## `UPROPERTY(NonTransactional)`

Indicates that changes to this property's value should not be included in the editor's *Undo* / *Redo* history.
{% endhint %}

{% hint style="info" %}

## `UPROPERTY(Replicated)`

Marks the property for replication. See [**Variable Replication**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) for more info.
{% endhint %}

{% hint style="info" %}

## `UPROPERTY(ReplicatedUsing=FunctionName)`

Binds a Rep Notify for the replicated variable. See [**Variable Replication**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) for more info.
{% endhint %}

{% hint style="info" %}

## `UPROPERTY(SaveGame)`

Indicates that this property should be included when the object is serialized to an **`FArchive`** with `ArIsSaveGame` set. See [**Game Saves**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) for more info.
{% endhint %}

{% hint style="info" %}

## `UPROPERTY(Transient)`

Indicates that this property is a **transient** value.&#x20;

Transient properties are temporary values that exist only during runtime—they’re not saved to disk or loaded back in. A typical example would be something like a variable that stores user input, such as throttle. There's no need to persist that data; it's only relevant while the game is running, and after that, it’s gone.
{% endhint %}

#### Meta Specifiers

{% hint style="info" %}

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

Exposes the property as a **Console Variable**. See [**Console**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) for more info.
{% endhint %}

{% hint style="info" %}

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

Specifies an alternative name for the property.&#x20;
{% endhint %}

{% hint style="info" %}

## `UPROPERTY(meta=(DisplayPriority=123))`

Sets the priority of the property in the **Details** panel. Lower numbers are placed higher.
{% endhint %}

{% hint style="info" %}

## `UPROPERTY(meta=(DisplayThumbnail=true))`

Specifies whether the property should have a thumbnail image in the **Details** panel.
{% endhint %}

{% hint style="info" %}

## `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`.
{% endhint %}

{% hint style="info" %}

## `UPROPERTY(meta=(ShowOnlyInnerProperties))`

When applied to a [**`USturct`**](https://unreal-voyage.github.io/docs/programming/cplusplus/constructs/ustruct/index.md) property, the **Details** panel will list out the inner properties of the `struct`:

<p align="center"><img src="https://413042066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDb1evVoYDUh1tShfU1sg%2Fuploads%2FSpyfWOvESgUPnGy4sYPc%2Fimage.png?alt=media&#x26;token=5226428a-8bac-4630-87bd-1a75f873d8b5" alt=""></p>

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

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

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

{% endhint %}

{% hint style="info" %}

## `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. Unreal will use the **docstring** of the property if this specifier is not present.
{% endhint %}

### The `UFUNCTION` Macro

The `UFUNCTION()` macro  is used to mark methods that the engine and the editor must be aware of. This includes functions that:

* Must be **callable** in the editor or [**Blueprints**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/blueprint/constructs/class).
* May be bound to delegates or implemented in [**Blueprints**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/blueprint/constructs/class) as [**events**](#events).
* Are intended for replicated [**remote procedure calls**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) (RPCs) in a networked game.
* May need to be queried via the `FindFunction()` method on the corresponding `UClass` instance.

The `UFUNCTION()` macro accepts a set of **specifiers** and **meta specifiers** that alter how the function behaves in the engine and the editor.

#### Specifiers

{% hint style="info" %}

## `UFUNCTION(BlueprintCallable)`

Exposes this function to [**Blueprints**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/blueprint/constructs/class).

<p align="center"><img src="https://413042066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDb1evVoYDUh1tShfU1sg%2Fuploads%2FHR2XltPiudrz35EO3pr2%2Fimage.png?alt=media&#x26;token=613ad65f-5e7c-432b-86f0-d7d869953f14" alt=""></p>
{% endhint %}

{% hint style="info" %}

## `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.

<p align="center"><img src="https://413042066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDb1evVoYDUh1tShfU1sg%2Fuploads%2FDqQ2LDCddZEsltWLwyxq%2Fimage.png?alt=media&#x26;token=a21079f0-a712-4c8c-a118-5e5b5d29f65c" alt=""></p>

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.
{% endhint %}

{% hint style="info" %}

## `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.

<p align="center"><img src="https://413042066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDb1evVoYDUh1tShfU1sg%2Fuploads%2Fvc25gTPytqyhZMwZs4CS%2Fimage.png?alt=media&#x26;token=66305dad-9b19-4eab-8f5d-e6041a6ba2bb" alt=""></p>
{% endhint %}

{% hint style="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**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) for more info.
{% endhint %}

{% hint style="info" %}

## `UFUNCTION(Client` / `Server)`

Marks the function is either a **Client** or **Server** RPC. See [**Replication**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) for more info.
{% endhint %}

{% hint style="info" %}

## `UFUNCTION(Reliable` / `Unreliable)`

Indicates whether the function should be replicated via **reliable** or **unreliable** channels. See [**Replication**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) for more info.
{% endhint %}

{% hint style="info" %}

## `UFUNCTION(WithValidation)`

Indicates that the RPC has a corresponding **validation** function, which must have the exact same signature except for a boolean return value, and the `_Validate` prefix.

{% code title="MyClass.h" %}

```cpp
UFUNCTION(Server, WithValidation)
void SomeFunction(float InValue);
```

{% endcode %}

{% code title="MyClass.cpp" %}

```cpp
bool UMyClass::SomeFunction_Validate(float InValue) { ... };
```

{% endcode %}

When the original function is called, `FunctionName_Validate` is called on the server and if it returns `true`, the server will continue to execute the original function. Otherwise, the call is dropped.&#x20;
{% endhint %}

#### **Events**

To declare a method that can be **overridden** in [Blueprints](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/blueprint/constructs/class), you need to use either one of the following specifiers: &#x20;

{% hint style="info" %}

## `UFUNCTION(BlueprintNativeEvent)`

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

<pre class="language-cpp" data-title="MyEventfulActor.h"><code class="lang-cpp">UFUNCTION(BlueprintNativeEvent)
void Damaged(float Damage, <a data-footnote-ref href="#user-content-fn-10">UPARAM(ref)</a> FHitInfo&#x26; HitInfo);
</code></pre>

The C++ implementation of the function is defined under the **`_Implementation`** suffix:

{% code title="MyEventfulActor.cpp" %}

```cpp
void AMyEventfulActor::Damaged_Implementation(float Damage, FHitInfo& HitInfo) { 
    ... 
}
```

{% endcode %}

The function above will show up as an **event** in the **Event Graph** of any [**Blueprint**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/blueprint/constructs/class) that extends the class:

<p align="center"><img src="https://413042066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDb1evVoYDUh1tShfU1sg%2Fuploads%2FsuhznGj4ad8Mmh7DFGlK%2Fimage.png?alt=media&#x26;token=3f7b28ac-87d4-4939-a300-3b02a79d3aa5" alt=""></p>

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

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

In this case, however, the function will not show up as an **event**, but as an **overridable** function:

<p align="center"><img src="https://413042066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDb1evVoYDUh1tShfU1sg%2Fuploads%2FZIVCfm25MIJ1d7opEgPq%2Fimage.png?alt=media&#x26;token=28233007-5628-4dea-b07a-4f78c5ed6c80" alt="" data-size="original"></p>

A subclass can negate this with `UFUNCTION(SealedEvent)`. This is equivalent to `final` in C++.
{% endhint %}

{% hint style="info" %}

## `UFUNCTION(BlueprintImplementableEvent)`

This specifier is just like **`UFUNCTION(BlueprintNativeEvent)`**, but it no longer requires a fallback C++ implementation. If the function is not overridden in a **Blueprint** subclass, it simply does nothing.

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.
{% endhint %}

#### Meta Specifiers

{% hint style="info" %}

## `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`.

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

<p align="center"><img src="https://413042066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDb1evVoYDUh1tShfU1sg%2Fuploads%2FDECIqboFjZbt5N6CEkTO%2Fimage.png?alt=media&#x26;token=363fae6c-487b-4fb5-8b14-0ea8821e82eb" alt=""></p>
{% endhint %}

{% hint style="info" %}

## `UFUNCTION(meta=(BlueprintProtected))`

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

{% hint style="info" %}

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

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

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

<p align="center"><img src="https://413042066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDb1evVoYDUh1tShfU1sg%2Fuploads%2FemKVaVTaTJanRoQFkUhh%2Fimage.png?alt=media&#x26;token=d2879bd6-02a2-4877-9937-989225bed650" alt=""></p>
{% endhint %}

{% hint style="info" %}

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

Specifies an alternate name for the function to be displayed in the editor.&#x20;
{% endhint %}

{% hint style="info" %}

## `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.

```cpp
UFUNCTION(BlueprintCallable, meta=(ExpandBoolAsExecs="ReturnValue"))
bool HealthBelowZero();
```

<p align="center"><img src="https://413042066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDb1evVoYDUh1tShfU1sg%2Fuploads%2FASotBao5uJSCT3ay74jZ%2Fimage.png?alt=media&#x26;token=d7606222-f85d-474f-914a-52177962244b" alt=""></p>
{% endhint %}

{% hint style="info" %}

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

Marks the function as a **latent action**.&#x20;

Latent functions need to accept a passed-by-value [`FLatentActionInfo`](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) parameter named `"VariableName"`.
{% endhint %}

{% hint style="info" %}

## `UFUNCTION(meta=(NotBlueprintThreadSafe))`

Excludes the method as a non-thread-safe function in a class marked with the `UCLASS(meta=(BlueprintThreadSafe))` specifier.
{% endhint %}

{% hint style="info" %}

## `UFUNCTION(meta=(ParameterName=DefaultValue))`

Specifies (or overrides) the default value for the named parameter in the **Blueprint** editor.
{% endhint %}

{% hint style="info" %}

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

Specifies an alternate name for the function's return value, instead of the default name which is `"ReturnValue"`.
{% endhint %}

{% hint style="info" %}

## `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. Unreal will use the docstring of the function if this specifier is not present.
{% endhint %}

#### The `UPARAM` Macro

The arguments of `UFUNCTION`s can be decorated with the **`UPARAM`** macro. This macro has 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.

```cpp
UFUNCTION(BlueprintCallable)
float AnotherFunction(
    float PassedByValueInput, 
    UPARAM(ref) FSomeStruct& PassedByRefInput, 
    FSomeStruct& PassedByRefOutput
);
```

#### 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 in C++. Note that in such cases, the definition ***must*** be present in the `.h` file.

```cpp
FORCEINLINE UArrowComponent * GetSpawnPoint() { return OpenFirePoint; }
```

### Instantiation <a href="#instantiation" id="instantiation"></a>

To instantiate a `UObject` subclass, you will need to use the `NewObject<T>(UObject* Outer)` function. The outer object will be responsible for the newly created instance. As long as the outer itself is still in memory, the engine assumes the inner object is still needed and keeps it from being garbage collected.

An example of this function in action is shown below.

```cpp
AShotgun* Shotgun = NewObject<AShotgun>(this);
```

The function can actually accept a `UClass*` to dynamically specify the type at runtime, which is useful when the exact class isn’t known at compile time:

<pre class="language-cpp"><code class="lang-cpp">T* NewObject(
    UObject* Outer, 
    const UClass* Class = T::StaticClass(), 
    FName <a data-footnote-ref href="#user-content-fn-11">Name</a> = NAME_None, 
    <a data-footnote-ref href="#user-content-fn-12">EObjectFlags</a> Flags = RF_NoFlags
)
</code></pre>

For example, assuming that `WeaponClass` is a class pointer to an `AWeapon` subclass:&#x20;

```cpp
AWeapon* CharactersWeapon = NewObject<AWeapon>(this, WeaponClass);
```

#### Subobjects

Subobjects are `UObject` instances that are created inside the constructor of a parent object. This pattern occurs frequently in Unreal—for example, when setting up [`UActorComponent`](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference)s inside an [`AActor`](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference). These objects are constructed along with their owner and treated as part of its internal hierarchy. Since they’re created during the class’s setup phase, you can’t use `NewObject`—you must use `CreateDefaultSubobject(FName SubobjectName)`, which ensures the engine registers them properly and maintains ownership. The function will return a pointer to the instance when successful.

<pre class="language-cpp"><code class="lang-cpp">ALamp::ALamp() {
    MeshComp = CreateDefaultSubobject&#x3C;UStaticMeshComponent>("<a data-footnote-ref href="#user-content-fn-13">Body</a>");
}
</code></pre>

The pointer to a subobject (in our example `MeshComp`) ***must*** be marked by `UPROPERTY`, otherwise, Unreal's garbage collector won't be able to trace its reference, and it will be garbage collected rather immediately. It should also be placed in an appropriate wrapper. See [**Object Pointers**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) to learn more.

<pre class="language-cpp"><code class="lang-cpp">UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Components")
<a data-footnote-ref href="#user-content-fn-14">TObjectPtr</a>&#x3C;UStaticMeshComponent> MeshComp;
</code></pre>

{% hint style="info" %}
Instead of `CreateDefaultSubobject`, you can use `CreateOptionalDefaultSubobject`, an alternative template function with a similar signature, which allows subclasses to override the parent's default subobjects using [`FObjectInitializer`](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference). See the [API Reference](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) to learn more.
{% endhint %}

### 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.

```cpp
AWeapon* Weapon = Cast<AWeapon>(Shotgun);
if (Weapon) {  // Weapon would be nullptr if cast fails
    ... // Do something with the valid weapon.
}
```

### Typedefs

The **`UObject`** class defines a couple of useful `typedef`s 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:

  ```cpp
  void AMyEventfulActor::BindToScoreChanged() {
      OnScoreChangedDelegate.BindUObject(this, &ThisClass::OnScoreChanged);
  }
  ```
* **`Super`** is a `typedef` for the class's parent class. This shortcut is often used to call the parent's functions in overridden methods:

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

### Serialization

{% hint style="warning" %}
This section isn’t finished yet — you could help improve it by [contributing](https://unreal-voyage.gitbook.io/reference/home#want-to-help)!
{% endhint %}

### Life Cycle Hooks

{% hint style="warning" %}
This section isn’t finished yet — you could help improve it by [contributing](https://unreal-voyage.gitbook.io/reference/home#want-to-help)!
{% endhint %}

### External Linkage

Within every module, there is a dedicated macro, **`MODULENAME_API`**, which is equivalent 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.

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.

[^1]: Required as the last `#include` by the [UHT](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/..#reflection-system).

[^2]: An example of a `UCLASS` specifier. See [below](#the-uclass-macro) for more info.

[^3]: The `MODULENAME_API` macro is akin to the standard `extern` keyword in C++ and marks the class for external linkage.&#x20;

    See [**External Linkage**](#external-linkage) for more info.

[^4]: The class name should be in **`PascalCase`** and prefixed with one of the [recommended prefixes](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/..#naming-conventions).

[^5]: Required to inject some code generated by the [UHT](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/..#reflection-system).

[^6]: An example of a `UFUNCTION` specifier. See [below](#the-ufunction-macro) for more info.

[^7]: An example of a `UFUNCTION` meta specifier. See [below](#the-ufunction-macro) for more info.

[^8]: An example of a `UPROPERTY` specifier. See [below](#the-uproperty-macro) for more info.

[^9]: An example of a `UPROPERTY` meta specifier. See [below](#the-uproperty-macro) for more info.

[^10]: Marks the argument as an input. See [below](#the-uparam-macro) for more info.

[^11]: An optional name for the object that can be used to [look it up](https://dev.epicgames.com/documentation/en-us/unreal-engine/API/Runtime/CoreUObject/UObject/FindObject/).

[^12]: See [here](https://dev.epicgames.com/documentation/en-us/unreal-engine/API/Runtime/CoreUObject/UObject/EObjectFlags) for available options.

[^13]: The name does not have to match the propery's name.

[^14]: A wrapper for a hard object reference.&#x20;

    See [**Object Pointers**](https://unreal-voyage.gitbook.io/reference/old-manuals/programming/cplusplus/constructs/broken-reference) to learn more.
