C++ Class Construct  «Prev 

Program Dissection in C++


//Calculate salary using static members.
class salary {
public:
   init(int b) { b_sal = b; }
   void  calc_bonus(double perc)
     { your_bonus = b_sal * perc; }
   static void  reset_all(int p)
     { all_bonus = p; }
   int  comp_tot() const
     { return (b_sal + your_bonus + all_bonus); }
private:
   int         b_sal;
   int         your_bonus;
   static int  all_bonus;     //declaration
};

//declaration and definition
int salary::all_bonus = 100;

int main(){
   salary  w1, w2;
    
   w1.init(1000);
   w2.init(2000);
   w1.calc_bonus(0.2);
   w2.calc_bonus(0.15);
   salary::reset_all(400);
   cout << " w1 " << w1.comp_tot() << "   w2 "
    << w2.comp_tot() << endl;
}

class  salary {
. . .
private:
   int        b_sal;
   int        your_bonus;
   static int all_bonus;     //declaration
};

There are three private data members. The static member all_bonus requires a file scope declaration. It can exist independent of any specific variables of type salary being declared.

init(int b) { b_sal = b; }

This statement assigns the value of b to the member b_sal. This member function initializes the base salary.
static void  reset_all(int p) { all_bonus = p; }

The modifier static must come before the function return type.
int  comp_tot() const
   { return (b_sal + your_bonus + all_bonus); }

The const modifier comes between the end of the argument list and the front of the code body. It indicates that no data member will have its value changed. Thus, it makes the code more robust. In effect, it means that the self-referential pointer is passed as const salary* const this.

salary::reset_all(400);

A static member function can be invoked using the scope resolution operator. It could also have been invoked as:

w1.reset_all(400);

but this is misleading, since there is nothing special about using the class variable w1.
The static keyword is used only in the class definition and needs to be omitted when the data or function member is defined outside the class.