Matthias Matthias - 3 months ago 24
C++ Question

Best Practice to initialize multiple Class Attributes in C++

I hope this question is not (too) subjective, as I am really interested in "a good" approach, and I haven't found what I am looking for online... So I have a C++ class, not too complex, but with a bunch of attributes. Now when I want to initialize them all via the class constructor, I end up with something like this:

ADynamicGameMode::ADynamicGameMode() : NumSpawnPoints(0),
ChallengeRating(0),
MinNumberOfBadBugsOnMap(0),
MaxNumberOfBadBugsTotal(0),
NumberOfBadBugsSpawned(0),
NumberOfBadBugsKilled(0),
BadBugSpawnInterval(0),
CommonSpidersKilled(0),
PoisonousSpiderKilled(0),
SniperSpiderKilled(0),
BigAssSpiderKilled(0),
MinChallengeRating(CR_MIN),
MaxChallengeRating(CR_MAX),
SpawnIntervalBaseValue(10),
MinBadBugsBaseValue(2),
MaxBadBugsBaseValue(10),
SpawnIntervalLoopModifier(0.5),
SpawnIntervalCrModifier(1.0),
MinBadBugsCrModifier(1.0), MaxBadBugsCrModifierCommon(0.8), MaxBadBugsCrModifierPoisonous(1.0),
MaxBadBugsCrModifierBigAss(1.3),
MaxBadBugsCrModifierSniper(1.5),
CommonCrBoundary(0),
PoisonousCrBoundary(20),
BigAssCrBoundary(40),
SniperCrBoundary(55),
FireflyPawn(nullptr),
BP_CommonSpider(nullptr),
BP_PoisonousSpider(nullptr),
BP_BigAssSpider(nullptr),
BP_SniperSpider(nullptr)
{
LastBadBugSpawnTime = std::numeric_limits<float>::lowest();
}


I feel that this is not the proper way in C++ of doing what I want. How do you deal with such a long list of attribues -- or is there even "the" C++ way?

Answer

Consider default member initialization:

class ADynamicGameMode
{
private:
    NumSpawnPoints = 0;
    ChallengeRating = 0;
    ....

or

class ADynamicGameMode
{
private:
    NumSpawnPoints {0};
    ChallengeRating {0};
    ....