TExcelTAD
Home › Unreal Engine 5 with C++ › How Reflection Works: UHT

How Reflection Works: UHT

UPROPERTY and its friends look like macros, and they are, but almost empty ones. In the engine headers, UPROPERTY(...) expands to nothing. The real work happens before the compiler runs:

  1. UnrealBuildTool (UBT) decides what to build and runs UnrealHeaderTool (UHT) on every module with reflected types.
  2. UHT parses your headers as text, finds UCLASS, UPROPERTY, UFUNCTION, USTRUCT, UENUM markers and their specifiers, and writes generated code:
    • ArenaWeapon.generated.h: the body that GENERATED_BODY() expands to (StaticClass(), Super typedef, constructors, RPC thunks, DECLARE_FUNCTION wrappers for Blueprint calls);
    • ArenaWeapon.gen.cpp: static tables that describe every property (name, type, flags, byte offset, metadata) and function, and register the class with the engine at startup.
  3. The C++ compiler then compiles your code together with the generated files.

At runtime each class is described by a UClass object holding a linked list of FProperty objects. The Details panel, Blueprints, the garbage collector, serialization and replication all walk those lists.

cpp
// Engine code: reading a property by name through reflection
#include "UObject/UnrealType.h"

void DumpFloats(UObject* Obj)
{
    for (TFieldIterator<FFloatProperty> It(Obj->GetClass()); It; ++It)
    {
        const FFloatProperty* Prop = *It;
        float Value = Prop->GetPropertyValue_InContainer(Obj);
        UE_LOG(LogTemp, Log, TEXT("%s = %f"), *Prop->GetName(), Value);
    }
}

// And by name:
if (FProperty* P = FindFProperty<FProperty>(AArenaWeapon::StaticClass(), TEXT("Ammo"))) { /* … */ }

This is also why UHT has rules: it is a parser of a C++ subset, not a compiler. It can't see through your own macros or templates, which is why a UPROPERTY can't be a std::vector and must use engine types it understands (TArray, TMap, TSet, TObjectPtr, TSubclassOf, FString, structs marked USTRUCT…).

A runnable model: macros as tables

Plain C++ can imitate the result of UHT with the X-macro trick: list the properties once in a macro, then expand that list several times with different definitions, once to declare the members and once to build a table of descriptors with offsetof. The table is a miniature UClass.

cpp · try it yourself
#include <cstddef>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>

// Flags, like CPF_Edit, CPF_BlueprintVisible, CPF_SaveGame in the engine.
enum Flags : unsigned { Edit = 1, BlueprintRead = 2, SaveGame = 4 };

enum class Type { Float, Int };
struct PropertyInfo { const char* Name; Type T; std::size_t Offset; unsigned Flags; };

// The "header": one line per UPROPERTY.   X(type, enum, name, default, flags)
#define WEAPON_PROPERTIES(X)                                 \
    X(float, Float, Range, 5000.0f, Edit | BlueprintRead)    \
    X(int,   Int,   MagazineSize, 12, Edit)                  \
    X(int,   Int,   Ammo, 12, BlueprintRead | SaveGame)      \
    X(float, Float, LastFireTime, -1.0f, 0)

struct Weapon {
#define DECLARE_MEMBER(type, e, name, def, flags) type name = def;
    WEAPON_PROPERTIES(DECLARE_MEMBER)
#undef DECLARE_MEMBER
};

// The "generated .gen.cpp": a static table describing Weapon.
const std::vector<PropertyInfo> WeaponClass = {
#define DESCRIBE(type, e, name, def, flags) {#name, Type::e, offsetof(Weapon, name), flags},
    WEAPON_PROPERTIES(DESCRIBE)
#undef DESCRIBE
};

std::string ValueText(const void* obj, const PropertyInfo& p) {
    const char* base = static_cast<const char*>(obj) + p.Offset;
    if (p.T == Type::Float) return std::to_string(*reinterpret_cast<const float*>(base)).substr(0, 7);
    return std::to_string(*reinterpret_cast<const int*>(base));
}

void SetByName(void* obj, const std::string& name, double v) {
    for (const auto& p : WeaponClass)
        if (name == p.Name) {
            char* base = static_cast<char*>(obj) + p.Offset;
            if (p.T == Type::Float) *reinterpret_cast<float*>(base) = static_cast<float>(v);
            else *reinterpret_cast<int*>(base) = static_cast<int>(v);
        }
}

int main() {
    Weapon w;
    SetByName(&w, "Ammo", 7);                       // what a Blueprint "Set Ammo" node does

    std::cout << "Details panel (Edit flag):\n";
    for (const auto& p : WeaponClass)
        if (p.Flags & Edit) std::cout << "  " << std::setw(13) << std::left << p.Name << ValueText(&w, p) << "\n";

    std::cout << "Save game (SaveGame flag):";
    for (const auto& p : WeaponClass)
        if (p.Flags & SaveGame) std::cout << " " << p.Name << "=" << ValueText(&w, p);

    std::cout << "\nAll properties with offsets:\n";
    for (const auto& p : WeaponClass)
        std::cout << "  +" << p.Offset << " " << p.Name << (p.Flags == 0 ? " (no flags)" : "") << "\n";
}
Details panel (Edit flag):
  Range        5000.00
  MagazineSize 12
Save game (SaveGame flag): Ammo=7
All properties with offsets:
  +0 Range
  +4 MagazineSize
  +8 Ammo
  +12 LastFireTime (no flags)

Everything the editor does with your class is a loop like these over a table. The engine's version is richer: flags for replication and GC, nested structs, containers, metadata strings, and functions with parameter lists. The idea is the same.

Note: LastFireTime has no flags here, but it is still in the table. In real Unreal a member without UPROPERTY() is not in the table at all, so the garbage collector, the save system and replication can't see it. For numbers that is often fine. For object pointers it is a crash waiting to happen; the next lesson shows why.

What this means day to day

  • Changing a reflected header means UHT runs again and generated code changes. That is why Live Coding can't always apply header changes; see Live Coding, UBT & UHT.
  • Errors from UHT appear before compile errors and mention the header and line: Unrecognized type 'std::vector', Missing '*' in Expected a pointer type, BlueprintReadWrite should not be used on private members. Read them first.
  • Generated code lives in Intermediate/Build/.../UHT. Opening a .gen.cpp once is instructive: you will recognise the table above.

Test yourself

What does the UPROPERTY(...) macro expand to in C++?

  1. A registration function call
  2. Essentially nothing; UnrealHeaderTool reads it from the source text and generates code
  3. A template
  4. A std::any wrapper

Why can't a UPROPERTY be a std::vector<int>?

  1. std::vector is slow
  2. UHT only understands engine types it knows how to describe, such as TArray
  3. The standard library is banned in Unreal
  4. Vectors can't be serialized in C++

In the X-macro model, what plays the role of UHT's generated tables?

  1. The struct members
  2. The WeaponClass vector of name/type/offset/flags descriptors
  3. SetByName
  4. main