Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding the static and const Keywords in C/C++

Tech Dec 2 10

static

The static keyword, when used to declare a varible, places that variable in the global (static) storage area. Initialized and uninitialized static variables are stored in separate regions within this area. If a static variable is not explicitly initialized, it is automatically initialized to 0.

For Local Variables

  • static extends the lifetime of a local variable. It is not destroyed when the function exits; rather, it persists until the program terminates.
  • A static local variable is initialized only once, when the function is first called. Subsequent calls do not reinitialize it—the initialization code is skipped.
  • Static local variables retain their value between function calls. The result from the previous call is preserved and used as the initial value for the next call.
  • Compared to global variables, static local variables are easier to maintain because they remain within the function's sccope (local scope), making them accessible only from within that function.

For Global Variables

  • static changes the linkage of a global variable to internal linkage. This means the variable is accessible only within the file where it is declared. It cannot be accessed from other files using extern declarations. To use such a variable in an external file, one effectively needs to include the entire source file that contains the static global variable definition—equivalent to rewriting the file's contents in the external file.
  • The purpose of static for global variables is to prevent name conflicts. Different files can define global variables with the same name without causing linkage errors, as each is confined to its own translation unit.

For Functions

The behavior of static for functions is identical to that for global variables: it gives the function internal linkage, limiting its visibility to the file in which it is defined.

Supplementary Knowledge: Memory Layout

  1. Stack Area: Memory allocated and deallocated automatically by the compiler (e.g., local variables, function parameters). Space is released when the scope exits.
  2. Heap Area: Memory allocated and deallocated by the programmer (e.g., malloc in C, new in C++).
  3. Global/Static Data Area: Global variables and static variables are stored together. Initialized global/static variables reside in one region, and uninitialized ones reside in an adjacent region. Memory is released when the program ends.
  4. Code Area: Stores the program's executable instructions.

static in C++

In C++, static retains all the properties it has in C, with additional functionality related to classes.

Static Member Variables

Static member variables (also called class variables) behave similarly to static local variables, but within the context of class instantiation:

  • Static member variables are stored in the global/static area, so they do not occupy memory within each class instance. Consequently, they cannot be defined inside the class declaration; they must be defined and initialized outside the class.
  • There is only one copy of a static member variable, shared by all instances (objects) of the class. Thus, they can be accessed using either the object-dot syntax (obj.variable) or the class-scope resolution syntax (ClassName::variable).
  • They are not destroyed when an object is destroyed; they persist until the program ends.
  • They are initialized only once, when the first object of the class is instantiated. Subsequent instantiations do not reinitialize them.
  • They are persistent across object lifetimes, meaning the value set by one object is retained for the next object.

This behavior mirrors the behavior of static local variables in C, with the function's activation replaced by object instantiation.

Example:

#include <iostream>
using namespace std;

class Rectangle {
private:
    int m_w, m_h;
    static int s_sum;

public:
    Rectangle(int w, int h) {
        this->m_w = w;
        this->m_h = h;
        s_sum += (this->m_w * this->m_h);
    }

    void GetSum() {
        cout << "sum = " << s_sum << endl;
    }
};

int Rectangle::s_sum = 0;  // Initialize static member

void test01() {
    Rectangle rect1(3, 4);
    rect1.GetSum();
    cout << "sizeof(rect1)=" << sizeof(rect1) << endl;
}

int main() {
    cout << "sizeof(Rectangle)=" << sizeof(Rectangle) << endl;
    test01();
    Rectangle rect2(2, 3);
    rect2.GetSum();
    cout << "sizeof(rect2)=" << sizeof(rect2) << endl;

    system("pause");
    return 0;
}

Output explanation:

  • sizeof(Rectangle) equals 8 (two int members), confirming s_sum does not occupy space in the class memory.
  • The summed area (18 = 12 + 6) demonstrates:
    • The static member s_sum is not destroyed when rect1 goes out of scope (at the end of test01).
    • s_sum is initialized only when rect1 is created, not again for rect2.
    • The value of s_sum persists from rect1 to rect2.

Static Member Functions

  • Static member functions (also called class methods) are shared by all objects of the class.
  • They can be defined inside or outside the class.
  • They can be called using the class name and scope resolution operator (ClassName::function()).
  • Crucially, static member functions do not have a this pointer. Since they belong to the class as a whole, rather than any specific instance, they do not know which object called them.
  • Consequently, static member functions can only access static member variables and other static member functions. They cannot access non-static member variables or non-static member functions because they lack the this pointer needed to identify a specific object.

Summary of interaction rules:

  1. Static members can freely access other static members (variables and functions).
  2. Non-static member functions can acces both static and non-static members.
  3. Static member functions cannot access non-static members (variables or functions).

Important note: Non-static member functions, static member functions, and static member variables all exist in only one copy per class and do not occupy memory in each object. However, non-static member functions know which object they are operating on via the implicit this pointer, which is provided by the caller. The this pointer points to the object that invoked the function.

const

While static deals with storage, lifetime, and scope, the const keyword primarily deals with access permissions, specifically making variables read-only.

const (Without Classes)

  • A const variable must be initialized explicitly at the point of declaration. Once initialized, its value cannot be changed.
  • A non-const variable can be implicitly converted to a const type when needed (e.g., when passing to a function that expects a const reference).

const (With Classes)

const Member Variables

  • const member variables must be initialized using the member initializer list in the constructor. (This is also true for references and class types that lack a default constructor.)
  • Each object instance has its own copy of const member variables. They are initialized when the constructor is called via the initializer list.

const Member Functions (Const Functions)

To understand const member functions, it is essential to understand the this pointer. this is a pointer constant (ClassName * const this), meaning it always points to the object that invoked the member function and its own address cannot be changed. It is an implicit first parameter of every non-static member function.

In a const member function, the this pointer becomes of type const ClassName * const this. This implies that neither the pointer itself nor the object it points to can be modified. In other words, inside a const member function, you cannot modify any of the object's member variables (except those declared mutable or static).

Mutable member variables: Variables declared with the mutable keyword can be modified even inside a const member function.

Static member variables: const member functions can modify static member variables because static members are not associated with any specific instance.

Const Objects

  • A const object can only call const member functions. It cannot call non-const member functions.
  • A const object cannot modify its own member variables, except for mutable members.
  • A const object can modify static member variables.

Non-const Objects

  • A non-const object can call both const and non-const member functions.
  • It cannot modify its own const member variables.

Example:

#include <iostream>
using namespace std;

class Person {
public:
    Person(int h) : h_(h) {}
    int m_ = 10;
    const int h_;
    mutable int n_ = 20;
    static int y_;

    void fun() {}
    void func() const {}
};

int Person::y_ = 40;

int main() {
    const Person p1(3);
    // p1.m_ = 20; // Error: cannot modify member of const object
    // p1.h_ = 30; // Error: const member cannot be modified
    p1.n_ = 40;    // OK: mutable member
    p1.y_ = 50;    // OK: static member
    // p1.fun();   // Error: non-const function cannot be called on const object
    p1.func();     // OK: const function

    Person p2(4);
    p2.m_ = 20;    // OK
    // p2.h_ = 30; // Error: const member cannot be modified
    p2.n_ = 40;    // OK
    p2.y_ = 50;    // OK
    p2.fun();      // OK
    p2.func();     // OK

    system("pause");
    return 0;
}

Other Uses of const

Similar to static, a const variable declared at file scope has internal linkage by default in C++. This means it is visible only within the file where it is declared. Other files cannot reference or use it via extern. Therefore, declaring const variables in a header file is safe—even if the header is included by multiple source files, each translation unit gets its own copy, avoiding symbol redefinition errors.

Tags: C++static

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.