Referencing a class inside a structure(present in that class)

Hello every one…

I got a class header containing a structure.

Is it possible to use a pointer to that class in the structure?

e.g.

I got a function present in the structure


const bool SetStackAmount(int32 &NewStackAmount)
	{
		const ABaseInventoryItem* BaseItem = GetDefaultItem();
		if (BaseItem->ItemType == EItemType::StackableItem || BaseItem->ItemType == EItemType::StackableUsableItem)
		{}
}

The name of the class this structure is present in is


ABaseInventoryItem

There is a compilation error


1>c:\users\srikant\documents\unreal projects\survivalgame\source\survivalgame\Inventory/Items/BaseInventoryItem.h(46): error C2027: use of undefined type 'ABaseInventoryItem'


Is there anyway to solve it?

A class must be declared before you can use pointers (or references) to it.
Can you move your structure after the class?
Otherwise, you’d usually use forward declarations of the class


class ABaseInventoryItem;

declare your stuct and member function,


stuct Stuff { void Member(ABaseInventoryItem* item); };

then move the implementation of your function after the definition of the class.



//class definition here
void Stuff::Member(ABaseInventoryItem* item)
{
//do stuff
}


Defining Struct Functions in the CPP of the releated UClass

Dear Envenger,

What I am saying holds true if you define a USTRUCT above the UClass that it is related to.

You can simply declare your struct function as normal in the .h, but instead of defining it as well, define it in the .cpp of your related class.


**ABaseInventoryItem.h**

**this**

//this is your USTRUCT function that wants to refer to the UCLASS below it


```

const bool SetStackAmount(int32 &NewStackAmount)
	{
		const ABaseInventoryItem* BaseItem = GetDefaultItem();
		if (BaseItem->ItemType == EItemType::StackableItem || BaseItem->ItemType == EItemType::StackableUsableItem)
		{}
}

```



**becomes this**



```

const bool SetStackAmount(int32 &NewStackAmount);

```



ABaseInventoryItem.cpp

Then in the .cpp you write this:

//Note the context is now your Struct name, not the Class


const bool FYourStructName::SetStackAmount(int32 &NewStackAmount)
	{
		const ABaseInventoryItem* BaseItem = GetDefaultItem();
		if (BaseItem->ItemType == EItemType::StackableItem || BaseItem->ItemType == EItemType::StackableUsableItem)
		{}
}


**Forward Declaration**

You could even forward declare your class name if you needed it in the function definition

.h


```

const bool SetStackAmount(class ABaseInventoryItem* Item);

```



and then define the rest in the .cpp of your ABaseInventoryItem.cpp

Why / How?

C++ just needs the .h declarations to all make sense, you can define stuff anywhere you want, including in separate .cpp files, as long as you include the relevant .h files.

Using forward declaration + defining UStruct functions in a .cpp you can more than do what you want.

:slight_smile:

Enjoy!

Rama