I am aware of the general guideline “Do not use const
inside classes,” but I have encountered situations where I am unsure about the proper declaration of variables. For example, consider the following code:
#include <cstdio>
#include <cstdint>
class Driver {
public:
/** Collection of I2C addresses */
enum class I2CAddress : uint8_t {
Address_0 = 0x0,
Address_1 = 0x1,
};
/** Constructor */
explicit Driver(I2CAddress i2cAddress) : Address(i2cAddress) {};
private:
/** Selected I2C address */
const I2CAddress Address;
};
int main() {
Driver driver {Driver::I2CAddress::Address_0};
return 0;
}
In this example, it makes sense for Address
to be constant, but I am wondering about the implications of marking it as const
:
-
Compiler Optimizations: Does marking a private member variable as
const
provide any compiler optimizations, or is it redundant since it cannot be externally modified? -
Error Prevention: While marking it
const
can prevent accidental assignments (e.g., using=
instead of==
in a comparison)? -
Optimal Implementation: For constants like this, is the example above the optimal implementation, or would it be better to have a
const
-free class and declare the object itself asconst
when needed? For instance:class Driver { public: enum class I2CAddress : uint8_t { Address_0 = 0x0, Address_1 = 0x1, }; explicit Driver(I2CAddress i2cAddress) : Address(i2cAddress) {}; I2CAddress getAddress() const { return Address; } private: I2CAddress Address; }; int main() { const Driver driver {Driver::I2CAddress::Address_0}; return 0; }
Which approach is more appropriate in terms of performance, maintainability, and best practices in C++?
geo66 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.