Adding C++ Class to UE4 Project
April 11, 2019

Throughout my tutorials involving C++ and Unreal Engine 4 I will often say (write?) "add a new class" or something close to this. In the documentation it's described one way to do this, from within the editor. The great thing about this process is that your new class will have the necessary boilerplate code automatically added into the generated files, not to mention the fact that the IDE solution files will also be updated. The new code will also be compiled for hot reload, which is a great thing since, in theory, the editor will be updated to "see" whatever you have just added. However sometimes you add some extra thing to the new code, compile and the editor refuses to see it. To solve that you have to close the editor, build the project again (luckily there is no new compilation here, just some cleanup) and then reopen the editor. Now, what happens when you want to add multiple classes? Going through this process is still valid but because the code is automatically compiled you will have to wait through each compilation process before adding a new class.

If you manually add classes to your project you will have full control over when the code will be compiled. What I usually do is this:

  1. Open the file browser and navigate to the project's directory.
  2. Go to the correct source directory and create there two text files (the .h and the .cpp). Usually the "correct directory" is: [project directory]/Source/[project name]
  3. Repeat step 2 for each class (or struct) that you want to add into the project
  4. Inside Visual Studio, right click in the solution explorer's correct "folder", Add -> Existing Item... and then select the two (or more files) created in step 2.

Why not use the Add -> New Item... or even Visual Studio's Class Wizard? They do work and I only avoid those because of the fact that Visual Studio always want to create the new files in the wrong directory (inside the Intermediate subdirectory). What this means is that for each .h/.cpp pair to be added you will have to remember to point Visual Studio to the correct location. While the project will build, there are a few problems with this:

I have presented here 3 slightly different ways of adding new C++ classes to your Unreal Engine project. All 3 have the same problem and that is the fact that you will have to add the boilerplate code to your new files. Visual Studio's Class Wizard at least add some code (the class declaration and definition) to the generated files. Don't worry too much if you don't know what this boilerplate code is, because with time you will learn where to look at as reference code and then copy/paste to your own files.

With all that said, I encourage you to experiment with the available approaches, see which one you like and then stick to it.