Josh Morrison
Josh Morrison

Reputation: 7636

Can Non-static function modify a static variable in c++

can Non-static function modify a static variable in c++

Upvotes: 9

Views: 14156

Answers (3)

j4x
j4x

Reputation: 3716

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; }
};

Upvotes: 1

justkt
justkt

Reputation: 14766

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.

Upvotes: 5

Ferruccio
Ferruccio

Reputation: 100718

Yes, a non-static member function can modify a static data member as long as the data member's visibility allows it.

Upvotes: 21

Related Questions