Working between references and pointers

I’ve been working with references and pointers for a few months now. But what I can’t seem to find out is how to work between them and pass-by-value variables.

In the function below, I try to set the value of Icon to the UTexture2D* returned by LoadTexture.

void StatusWidget::GetProperties(UTexture2D& Icon)
{
	if (Content)
	{
		Icon = LoadTexture(Content->Properties.Icon);
	}
}

I get an error that

No operator “=” matches these operands. Operand types are: UTexture2D = UTexture2D *

If I try to dereference it. It says that the operator of UTexture2D.h is inaccessible.

How would I go about making VariableType& = VariableTypeD* ?

Another one I’ve been noticing is I can’t make a pointer variable = a pass-by-value variable, for example:

UTexture2D Icon;
UTexture2D* IconRef = *Icon;

no operator matches these operands
operand types are: * UTexture2D

I appreciate the help.

Assuming LoadTexture return UTexture2D*. How about this?

UTexture2D* StatusWidget::GetProperties()
{
	if (Content)
		return LoadTexture(Content->Properties.Icon);

	return nullptr;
}

If you just wanna return a value, why don’t just use a returning function?

1 Like

This is because Icon is already a constructed object that was passed in (since it is passed by reference) and now you’re trying to copy the instance returned from LoadTexture() into Icon. If there is no copy assignment operator (operator ‘=’), this fails.

If you don’t want to copy the object, but instead return a pointer, do what @Hexavx suggestions.

You need to use & to get the address of an object for a pointer:

UTexture2D Icon;
UTexture2D* IconPtr = &Icon;

Trying to do *Icon goes the other way, getting the object pointed to by Icon when Icon is a pointer.

References and pointers can be confusing, especially since ‘&’ is used as both a type specifier and an address-of operator.

1 Like

These are both great solutions and help me with understanding pointers and refs. I’ll apply @Hexavx 's solution :slight_smile:

Let say for argument’s sake, I want to make a function that returns two UTexture2D or other assets passed as args. How could I make that work (if at all)?

void StatusWidget::GetProperties(UTexture2D& Icon, UTexture2D& Background)
{
	if (Content)
	{
		Icon = LoadTexture(Content->Properties.Icon);
		Background = LoadTexture(Content->Properties.Background);
	}
	return;
}

Use UTexture2D* &Icon

void StatusWidget::GetProperties(UTexture2D* &Icon, UTexture2D* &Background)
{
	if (Content)
	{
		Icon = LoadTexture(Content->Properties.Icon);
		Background = LoadTexture(Content->Properties.Background);
	}
}
3 Likes

Makes sense. Thank you!