Originally I had m_damage as a class member in the base class Projectile, assigned the value in the initializer list in each derived class and had a single getter function in the base class.
But then I realized I dont need every instance of the derived classes holding a copy of m_damage since it was the same value for all instances of each derived class, so I needed to make the value static
and have each derived class return it in a virtual
function override.
After researching online and on here I believe inline static const
variable is the way to go. But is there any benefit to having it as a class member or class constant? or is there another better way to do it? I only want the value accessed via the private virtual function in Projectile.
projectile.h file
class Projectile
{
private:
virtual int getDamage() const = 0;
}
rocket .h file
class Rocket : public Projectile
{
private:
// inline static const auto ROCKET_DAMAGE = 400; <---- make it a class member?
virtual int getDamage() const final override;
}
rocket .cpp file
// inline static const auto ROCKET_DAMAGE = 400; <---- make it a class constant?
int Rocket::getDamage() const
{
return ROCKET_DAMAGE;
}
From an API design perspective, a constant is an implementation detail. Therefore, you may want to hide this implementation detail – i.e., the constant – behind the definition of a member function in the .cpp
file as you already have.
In rocket.hpp
:
class Rocket: public Projectile {
private:
virtual int getDamage() const final override;
};
In rocket.cpp
:
static constexpr auto ROCKET_DAMAGE = 400; // not exposed to client
int Rocket::getDamage() const {
return ROCKET_DAMAGE;
}
Note that having the constant ROCKET_DAMAGE
as a data member as in the example below exposes it to the client:
class Rocket: public Projectile {
private:
inline static const auto ROCKET_DAMAGE = 400;
};
The constant may be compiled into the client's code. This would imply that the client code would need to be recompiled every time you change the value of the constant ROCKET_DAMAGE
.
In contrast, if the constant ROCKET_DAMAGE
is not exposed to the client through the header file because it is hidden in the .cpp
file (as in the former case), changing the value of the constant can't possibly require the recompilation of client code.