Reference Member variable

I want to declare a member variable as a reference and instantiate it in the constructors initialization list. How can I do this with a class deriving directly from UObject?

Example:

class UtidBinaryTree;

UCLASS()
class UtidLeafNode : public UObject 
{
	GENERATED_UCLASS_BODY()

public:

        UtidLeafNode(UtidBinaryTree& a_tree);

        UtidBinaryTree& Tree;

};

The problem is that I don’t know if there is a way of overloading the required FObjectInitializer constructor. Is there another way to achieve this?

Hi,

i can be wrong, but isn’t

UtidBinaryTree& Tree;

a reference declaration? as i know references can’t be null because they always refer to any existing objects, note that reference in C++ is more safer version of pointers, but they have more limitations, so you probably can use just a pointer

UtidBinaryTree* Tree;

also note that & symbol have many meanings in C++ and in line

 UtidLeafNode(UtidBinaryTree& a_tree);

& is operator, while at bottom line it’s used to indicate reference

Thanks for your reply happyhorror. In this case I want to use a reference as the lifetime of object BinaryTree is intended to outlive the lifetime of object LeafNode. By using a reference, it ensures that LeafNode cannot exist unless it is owned by a BinaryTree, and by design, this makes sense. In standard C++, using a mem-initializer-list one can instantiate reference members as such:

UtidLeafNode::UtidLeafNode(UtidBinaryTree& a_tree)
	: Tree(a_tree)
{

}

This is commonly used to instantiate const member variables.

I just don’t know how to achieve this with UE4, as you can’t use a custom constructor with your own parameters.

Yes, unfortunately UE4 has no support for custom constructors. I’ve had to use the workaround of constructing my objects during BeginPlay(). This at least allows you to override references to assets in child classes, whereas if you try to do this in the Constructor, it will use the parent class references due to the order of Constructors being called.