Static Members of a Class/Structure

Static Data Members

  • Declared using the static storage class modifier.
  • Shared by all instances of a class; stored in one place.
  • Contrast with non-static members, which are created per object.
  • Allows class-specific data not tied to an instance to exist within the class scope.
  • Accessed via class_name::variable.
  • Context resolution operator :: is used for access.
  • Optional within class methods.
  • Must be explicitly initialized in the global scope.
  • Initialization sequence follows declaration order.
  • **Example (CParser):**

    class CParser { public: static int s_words; static int s_symbols; };
    int CParser::s_words = 0;
    int CParser::s_symbols = 0;
    

    Static const Data Members

  • Can be declared with the const keyword.
  • Must be initialized globally with the const keyword.
  • **Example (CStack):**

    class CStack { private: static const int s_max_length; };
    const int CStack::s_max_length = 1000;
    

    Pointer this

  • Refers to the current class instance.
  • Available only in non-static methods.
  • Static functions cannot access non-static members or use this.
  • Static Methods

  • Declared using the static modifier before the return type within the class.
  • Can only access static members/methods of the class.
  • **Example (CStack::Capacity):**

    class CStack { public: static int Capacity(); };
    int CStack::Capacity(void) { return(s_max_length); }
    

    **Accessing Static Methods:**

  • object.static_method()
  • ClassName::static_method()
  • const Correctness

  • Applies to non-static member functions.
  • Indicates the function does not modify implicit class members.
  • Ensures compiler checks for consistency.
  • const modifier placed after the argument list in declaration and definition.
  • Static functions cannot be declared const as they don't operate on an instance.
  • **Example (CRectangle::Square):**

    class CRectangle { public: double Square(void) const; };
    double CRectangle::Square(void) const { return(Square(m_width,m_height)); }
    

    Optimization

  • Compilers may optimize const objects by placing them in read-only memory.