Static Class Members

Introduction

  • It is sometimes necessary for all the objects of a particular class type to access a global object.
  • However, making the object global violates encapsulation: The object exists to support the implementation of a particular class abstraction.
  • If the object is global, general user code can modify the value. Rather than defining a generally accessible global object, a class can define a class static member.
  • Unlike ordinary data members, a static data member exists independently of any object of its class; each static data member is an object associated with the class, not with the objects of that class.

Example

class Account 
{
     public:
         // interface functions here
         void applyint() { amount += amount * interestRate; }
         static double rate() { return interestRate; }
         static void rate(double); // sets a new rate
     private:
         std::string owner;
         double amount;
         static double interestRate;
         static double initRate();
};

Accessing private static variables

  • The best way to access a private static variable is to use a public static function.

Example

class Something
{
private:
    static int s_nValue;
public:
    static int GetValue() { return s_nValue; }
};
 
int Something::s_nValue = 1; // initializer
 
int main()
{
    std::cout << Something::GetValue() << std::endl;
}
  • Static member functions can only access static member variables.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.