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!