This was just a question I was wondering about in terms of best practice. I am writing a small C++ program that uses an interface to implement a function.
In the class that uses the interface (i.e. inherits from the interface class), is it bad practice for me to use member variables so I don't have to keep re-declaring them every time the function comes into scope?
Say we have this interface:
class base{
public:
virtual ~base() {};
virtual int method(int num) = 0;
};
And the following class inherits it to implement the method function.
class usesinterface : public base {
public:
usesinterface() {};
virtual int method(int num){ // Always adds 5 to the number
return num_ + num;
}
private:
int num_ = 5;
};
Is storing num_
as a class member bad practice or considered wrong? Does it make more sense to write:
virtual int method(int num){
const int number = 5;
return number + num;
}
I am aware you can just write + 5 to save the hassle for this example but this is just a simplified version of a problem I am looking at.
EDIT 1:
In reality, the variable I am storing in my class / re-defining every function call is a lookup table that is only used within this singular function call. However, if I put it in the function, the function itself becomes very verbose (much worse code readability) and without optimization I believe it would continually re-allocate the lookup table.
const
ness of your example suggest it is