can Non-static function modify a static variable in c++
3 Answers
Yes, see this example for a small sample program.
Conversely a static function cannot modify a regular member variable the way a regular member function can.
2 Comments
some_instance.some_member = some_value. It's just that a static member function has no this, and unlike a non-static member function, just naming some_member doesn't implicitly mean this->some_member. So the static member function needs to get an instance from somewhere - a non-static member function has one handy and has a shorthand way of specifying the members of it.Yes you can.
Think of "static members" as if they were attributes that characterize the class while "non-instance members" characterize instances.
Classes define a concept while instances are occurences of this concepts.
A silly example is the class Human is a concept while you, Andy, is an instance. You are one human among 6 billion others.
Human concept says that all humans have limbs, head, eyes and so on. Those are instance fields. Every human instance has its own limbs, head, eyes...
I can specialize the human concept according to his/her profession.
Lets consider a ComputerEngineer class that defines, obviously, computer engineers.
Any instance of computer engineer is a human and still has limbs, head, eyes...
The ComputerEngineer class, however, can be modeled so that it has a qualifier (or attribute) that says the minimum salary that the category sindicate allows. Lets call it minimumWage
This is a situation were the same attribute must have a common value for all the class instances.
Note that although this minimumWage is not an instance member and cannot have different values for each instance, it is still related to the concept, so it is reasonable that it can be accessed.
The following fake code is valid in the sense of having an instance method accessing a static member:
class Human
{
protected:
Limb leftArm;
Limb leftLeg;
Limb rightArm;
Limb rightLeg;
};
class ComputerEngineer : public Human
{
protected:
static double _minimumWage;
double _wage;
public:
wage( double w ) // non-static member function can only be called by instances.
{
if ( w < minimumWage )
throw "You're gonna have trouble with the union!";
_wage = w;
}
minimumWage( double w )
{ _minimumWage = w; }
};
1 Comment
ComputerEngineer::_wage = w instead of just _wage = w?