Diference between SetupPlayerInputComponent in .h and .cpp files

Hi guys, I saw the code of the FirstPerson project and I noticed that in the .h file the SetupPlayerInputComponent is declared like this:

virtual void SetupPlayerInputComponent(UInputComponent* InputComponent) override;

and in the .cpp file:

void AFirstPersonCharacter::SetupPlayerInputComponent(class UInputComponent* InputComponent)

I’m new in all of this and maybe this is more about the c++ syntax, but I cant find anywhere why, unlike the .h, in the .cpp file the parameter InputComponent is declared with the class keyword. Thanks!

The use of class in front of a type name is forward declaring the type. This would normally be done at the top of a header file but the Unreal standard seems to be to do it where it’s needed. The reason for this is so you don’t need to include other headers inside the header possibly creating circular header dependencies. If your only declaring you want to use some type, like in a function declaration, the compiler just needs to know that type exists, not it’s full details and definition.

As for why it’s used in the .cpp file… I have no idea! This should never be needed in a .cpp file since you have to include the appropriate header defining the type. The compiler needs to see the full class definition before you can use that type inside the function.

I’m guessing this is a mistake, if you generate function definitions using Visual Assist, which I think Epic use, the class part will show up in the automatically generated function definition. Normally you would just delete this but I guess it doesn’t matter if you leave it.

If you want to know more about forward declarations check out the wikipedia article or a C++ book.

Ya había leído acerca del forward declaration, por eso me parecía extraño que esté en el .cpp. Thanks!

I don’t speak spanish, (or portuguese?) but you’re welcome! Please accept my answer if it’s answered your question :slight_smile:

There are cases where a forward declaration in a .cpp file make sense. As you said, you must include the appropriate header before using the members of that type. However, if you are (for example) accepting a pointer to that type and then simply passing the pointer to another class, without dereferencing it, then you do not need the complete class definition.

This may seem like a pretty rare situation–and it is probably is–but it’s also exactly the situation that occurs when Unreal first creates a file, and the only use of the parameter is to pass it on to the super-class method.