Can we initialize a const member(float) in class constructor?

Hi everyone! I’m a beginner in C++ and UE4, trying to learn and practice more coding. Today I bumped into a problem. I knew we could initialize a const member of a class in C++ like this:


Class EgClass(){
protected: const float fConstVar; //declare the const variable in header
 


 public: EgClass() : fConstVar(10.0f){ //initialize fConstVar's constant value to be 10, inside the constructor initialization list
//constructor
  }
 


 };

But when I try the same thing in Unreal (4.24), I get the Error - ‘EgClass::fConstVar’: an object of const-qualified type must be initialized. Here is my code:


**//header file, EgClass.h**
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "EgClass.generated.h"

class USphereComponent;

UCLASS()
class FPSGAME_API EgClass: public AActor
{
    GENERATED_BODY()

public:    
    EgClass();

protected:
    const float fConstVar;
};

**//cpp file, EgClass.cpp**
#include "EgClass.h"

EgClass::EgClass() : fConstVar(10.0f)
{ //constructor body
 


 }


Why does this fail? This should be following the exact C++ manner right? How can I do something like this in UE?? With this not working, I tried to declare and define fConstVar at the same time in the same place, the header. So I changed my header code to be:

const float fConstVar = 10.0f;

And also delete my constructor initialization list. This time it worked. BUT I heard people say that I shouldn’t use const var in a header file if it was included in several source files. That was because then the variables would be defined once per source file (translation units technically speaking), taking up more memory than required.

So I wanted to go back to the constructor initialization list way. I tried to play with the code, and something even weirder happened in my experiments. What I did was that I declared and defined fConstVar in the header first, with a DIFFERENT value (eg. 5), then I initialized it again in the constructor initialization list (with a value of 10) . To my surprise, there was no error and the final value of fConstVar was 10(defined in initializer), instead of 5(defined in header). Did this mean the value of a const variable changed after it was defined in a header file?! My code was like:


**//header file, EgClass.h**
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "EgClass.generated.h"

class USphereComponent;

UCLASS()
class FPSGAME_API EgClass: public AActor
{
    GENERATED_BODY()

public:    
    EgClass();

protected:
**const float fConstVar = 5.0f;**
};

**//cpp file, EgClass.cpp**
#include "EgClass.h"

**EgClass::EgClass() : fConstVar(10.0f)**
{
//constructor body
}


I’m confused by all these results. Can anyone explain to me why all these are happening?

How should I declare and define a const class variable properly in UE? And should I just declare and define const variables in the header file? It works but does it really cause problems if the header file is included in multiple source files?

Thank you very much! I appreciate your help and patience!

  1. Show the error log.
  2. People are confusing you. Const means const. Not the SAME in every instance. static means the same, static const means it is treated in essence as a #define, and only exists at compile time.

It is perfectly legal to have a const, and const & in a cpp class. They must be initialized in the constructor, and cannot be treated as mutable any where in code.

Most likely the error you are seeing is NOT a compiler error, but rather an Unreal Header Tool error. The header tool parses the headers, and generates the reflection code, among other things. This is the GENERATED_BODY() macro.

Post the build log so people who do know what it means can then tell you.

Cheers.

Thanks for the reply, but it seems Unreal doesn’t allow me to initialize const variable in the constructor initializer (of a class derived from Uobject). Here are my VS output log when I try to build the project, some names are changed in the actual project:


1>Building 6 actions with 12 processes...
1> [1/6] FPSBlackHole.gen.cpp
1>D:\Projects\StealthGame\Intermediate\Build\Win64\UE4Editor\Inc\FPSGame\FPSBlackHole.gen.cpp(124): error C2789: 'AFPSBlackHole::fForceToApply': an object of const-qualified type must be initialized
1> D:\Projects\StealthGame\Source\FPSGame/Public/FPSBlackHole.h(34): note: see declaration of 'AFPSBlackHole::fForceToApply'
1> [2/6] FPSGame.init.gen.cpp
1> [3/6] FPSBlackHole.cpp
1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.MakeFile.Targets(44,5): error MSB3075: The command ""D:\Game\Epic Games\UE_4.24\Engine\Build\BatchFiles\Build.bat" FPSGameEditor Win64 DebugGame -Project="D:\Projects\StealthGame\FPSGame.uproject" -WaitMutex -FromMsBuild" exited with code 5. Please verify that you have sufficient rights to run this command.
1>Done building project "FPSGame.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Here is the error list in VS:


Severity    Code    Description    Project    File    Line    Suppression State
Error    C2789    'AFPSBlackHole::fForceToApply': an object of const-qualified type must be initialized    FPSGame    D:\Projects\StealthGame\Intermediate\Build\Win64\UE4Editor\Inc\FPSGame\FPSBlackHole.gen.cpp    124    
Severity    Code    Description    Project    File    Line    Suppression State
Error    MSB3075    The command ""D:\Game\Epic Games\UE_4.24\Engine\Build\BatchFiles\Build.bat" FPSGameEditor Win64 DebugGame -Project="D:\Projects\StealthGame\FPSGame.uproject" -WaitMutex -FromMsBuild" exited with code 5. Please verify that you have sufficient rights to run this command.    FPSGame    C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.MakeFile.Targets    44    


Since I cannot build the project, I can’t launch Unreal editor so I don’t have the Unreal error log.
I just want to declare a const variable in the class header, then initialize it in the class constructor initializer. Hope there’s a way, Thanks!

Apparently C++ needs there to be a default value in case there is no default constructor.
Hence why this works:



protected:
    const float fConstVar = 5.0f;
};

//cpp file, EgClass.cpp

#include "EgClass.h"
EgClass::EgClass() : fConstVar(10.0f)
{
    //constructor body
}


Guess that means this would work as well:
.h:



UCLASS()
class FPSGAME_API EgClass: public AActor
{
    GENERATED_BODY()

public:    
    EgClass();

protected:
    const float fConstVar;
};


.cpp:



#include "EgClass.h"

const float EgClass::fConstVar = 5.0f;

EgClass::EgClass()
{
    // constructor body
}


Hmm… well there you go.

Thank you very much!! Now I understand this lol! So basically for some reason, C++ in unreal wants to make sure that const var is never undefined. Thus the value we gave in the header or outside class is a default safety value. And when we actually use the constructor initializer list, it’s the value we will set to the const var and remains unchanged for the rest of the game!

Thanks for the explanation! Almost gave up on this weird difference between raw C++ and unreal C++! :smiley: