Reputation: 944
Suppose I have a class Sensor
as shown below:
class Sensor
{
public:
Sensor();
array <float, 3> marker_pos(float, float, float);
private:
float range;
float phi;
array <float, 3> temp;
int flag = 0;
};
The variables range
and phi
are properties or variables of the sensor object. But the variables temp
and flag
are just normal variables that are to be used inside the function marker_pose
.
1. Is it bad practice to define/declare temp
and flag
inside the class ?
2. If I define/declare them inside the function marker_pose
, it will be defined every time I call that function. Is that a good idea?
3. What will be the best practice to follow in such situations ?
Upvotes: 0
Views: 198
Reputation: 9800
In C++, you have to declare variables as late as you can (ie: as deep in scope as you can).
Minimize the life span
of different variables may enhance the visibility of your code and ease the debug and maintenance of your program.
Upvotes: 0
Reputation:
You should always define variables at the minimum possible scope. So if variables are only used inside a function, they should be defined in the function, not in the class.
Upvotes: 5