Consider the following:
namespace MyNamespace{
class MyClass {
public:
// Public area
private:
// Private area
protected:
// Protected area
}; /* Class */
} /* Namespace */
And consider that I would like to define a constant which is specific for my class. I usually do the following:
namespace MyNamespace{
// Constants
const int MYINT = 12;
const std::string MYSTR = std::string("Hello");
// Class definition
class MyClass {
public:
// Public area
private:
// Private area
protected:
// Protected area
}; /* Class */
} /* Namespace */
In this way I can get my variable in this way (somewhere in my code):
MyNamespace::MYINT;
MyNamespace::MYSTR;
Is this a good practice?
Considering that constants can be treated in several ways (for example numeric constants are often treated using enum
), what is the best approach to define a constant (related to a class, but that can be also useful somewhere else)?
Thankyou
To declare a constant variable in C++, the keyword const is written before the variable's data type. Constant variables can be declared for any data types, such as int , double , char , or string .
A constant, like a variable, is a memory location where a value can be stored. Unlike variables, constants never change in value. You must initialize a constant when it is created. C++ has two types of constants: literal and symbolic.
You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.
A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.
If you want the constants specific to the class and also want them to be useful somewhere else as you said, possibly outside the class, then define them as static
member data in the public
section of the class:
//.h file
class MyClass
{
public:
//constants declarations
static const int MYINT;
static const std::string MYSTR;
};
//.cpp file
//constants definitions
const int MyClass::MYINT = 12;
const std::string MyClass::MYSTR = std::string("Hello");
Usage (or access):
std::cout << MyClass::MYINT << std::endl;
std::cout << MyClass::MYSTR << std::endl;
Output:
12
Hello
Online Demo: http://www.ideone.com/2xJsy
You can also use enum
if you want to define many integral constants and all of them are somehow related, for example this:
class shirt
{
public:
//constants declarations
enum shirt_size
{
small,
medium,
large,
extra_large
};
};
But if the integral constants are not related, then it wouldn't make much sense to define them as enum
, in my opinion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With