Why can't we forward declare IOnlineSessionPtr?

Hi there,

I’m so used to forward declaring classes in the header file and then typing the include in the source file that I just did that automatically when asked to make our IOnlineSessionPtr variable a member variable. But doing so gives me the error:

error C2079: ‘UMultiplayerSessionsSubsystem::OnlineSession’ uses undefined class ‘IOnlineSessionPtr’

Tried Googling but couldn’t find a similar question being posed. Would just be curious to know what makes this different to any other class type that you’d usually forward declare that makes this impossible, as I know avoiding includes in the header file when you can is good practice.

Any help would be appreciated, thanks!

Not seeing your code, I’m attempting an explanation based on assumptions and hoping it did not end up too quirky:

With forward-declared classes, the compiler does not know what the class looks like when looking at your usage of it.

When processing your own class declaration, one of the issues the compiler needs to resolve is how much memory each member variable of your class takes. When a member variable is only a pointer to an instance (i.e., value) of a class, the size does not matter, because all pointers (for a given context/architecture) are the same size. That’s why forward declaration is ok in such a case.

But in the case at hand, your member variable of type IOnlineSessionPtr is not a pointer at the syntax level (no asterisk). We humans can understand from the type name that each value of this type is some kind of pointer itself, but it is not a pointer on the C++ language level, which may be confusing. At runtime, an instance of your class will have a value in this field that is itself of the type IOnlineSessionPtr, not a pointer to such a value. The compiler needs to know what the name IOnlineSessionPtr means in order to determine the memory needed for a member variable that has this type.

2 Likes

IOnlineSessionPtr is not a class, it’s a typedef. As per the documentation it is a forward declaration already. It’s the same as typing

TSharedPtr<class IOnlineSession, ESPMode::ThreadSafe>
2 Likes

Thanks so much for the detailed reply, that puts it all in context as far as how forward declarations work, and along with DanM’s response it now makes sense as to why forward declaration wouldn’t be appropriate here.

Thanks again

1 Like

Thanks Dan, hadn’t heard of typedef’s before so just done some reading and that makes more sense now.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms