I'd love some feedback on the C++ base class shown below. It's basically a toy problem for a fake video game where the monsters that you have to avoid will all be sub-classed from the class shown below.
I'm particularly interested in feedback on the way I handled the character_count
counter, which is meant to count the total number of monsters created (for simplicity, I'm assuming there is no need to ever decrement the counter): I'm practising "Avoid initialization order problems across translation units by replacing non-local static objects with local static objects." From Item 4 of Effective C++ by Scott Meyers (if you have the book and are going to look, the bit I quoted is the summary he provides for the last third of Item 4... there are two other points he makes earlier in the item).
Character.h
#pragma once
enum CharacterType { kCharacterBaseClass, kGhost, kGoblin, kVampire };
struct CharCount {
int character_count = 0;
};
class Character {
public:
explicit Character(CharacterType type = kCharacterBaseClass);
static CharCount &CharacterCount();
[[nodiscard]] CharacterType GetType() const;
virtual void Animate() const;
protected:
CharacterType type_;
};
Character.cpp
#include "GmChrctrs/Character.h"
#include <iostream>
Character::Character(CharacterType type) : type_(type) {
++Character::CharacterCount().character_count;
}
CharCount &Character::CharacterCount() {
static CharCount char_count;
return char_count;
};
CharacterType Character::GetType() const { return type_; }
void Character::Animate() const {
std::cout << "generic character is animated" << std::endl;
}
Character
and have it tick up on constructor calls and tick down in destructor calls. Alsoint
is a poor choice for counting things. Depending on the expected amount of instances I'd use anunsigned int
orunsigned long
. Also I feel likeGoblin
,Vampire
andGhost
should be subclasses ofCharacter
. \$\endgroup\$unsigned int
instead ofint
hardly helps. If ~32,000 isn’t enough, uselong
or one of the types in<cstdint>
. \$\endgroup\$