Issue
This Content is from Stack Overflow. Question asked by codingnoobs
I used Macros at top of class to tell what is 1 and 45.00 instead of just writing magic numbers.
Question is why using Macros in following class (see the default constructor) is not a good idea? Why using const LIMIT_UNDER = 1 better? I think there is no difference.
But if I do use that constant at class data member level(global const is not a good thing we know), i.e.const int LIMIT_UNDER,
will I initialise it using constructor initializer list?
Class details:-
The Cube class which I have to calculate volume also. The class can have a user input of FLOAT length, width and height in between minimum 1 to maximum 45.00. Otherwise if user inputs any other numbers its all sides would be 1.
so it will be like
// Use MACRO or CONST???
#define LIMIT_UNDER 1
#define LIMIT_UPPER 45.00
class Cube {
float height;
float width;
float length;
public:
// Write setter getters here
// default constructor
Cube() {
// default constructor puts default values
height = width = length = LIMIT_UNDER;
// Other code of class...
)
'''
Solution
#define
constants in header files are generally considered bad because they pollute all files that happen to include that header. Even worse, their value could be changed by other files via #undef
.
Instead of using globally accessible symbols, try to keep things local to the scope in which they matter. For example:
class Cube {
static constexpr float minLimit = 1.f;
static constexpr float maxLimit = 45.f;
float height = minLimit;
float width = minLimit;
float length = minLimit;
};
This will also implicitly create a constructor that initialises the members to the default value. No need to write a constructor manually.
This Question was asked in StackOverflow by codingnoobs and Answered by bitmask It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.