Fundamentals 17 min read

Mastering const and static in C++: When and How to Use Them

This article provides a comprehensive guide to the const and static modifiers in C/C++, covering their distinct purposes, usage with variables, pointers, functions, and class members, and answering common interview questions with clear explanations and practical code examples.

Deepin Linux
Deepin Linux
Deepin Linux
Mastering const and static in C++: When and How to Use Them

1. const keyword: read‑only qualifier

The const qualifier makes an object immutable after initialization, acting like a read‑only lock for variables, pointers, function parameters, and member functions, thereby improving code safety and readability.

1.1 const applied to variables

const int num = 10;
num = 20; // compilation error: cannot modify a const variable

Attempting to assign a new value to num triggers a compile‑time error, preventing accidental changes and making intent explicit.

1.2 const applied to pointers

Two distinct cases exist:

Pointer to const data : const int *ptr allows the pointer to change the address it points to, but the pointed‑to value cannot be modified through the pointer.

Const pointer : int *const ptr fixes the pointer address while permitting modification of the pointed‑to value.

1.3 const applied to function parameters

void print(const std::string &str) {
    // str += "test"; // error: cannot modify const reference
    std::cout << str << std::endl;
}

Using const on parameters prevents unintended modifications inside the function.

1.4 const applied to member functions

class MyClass {
private:
    int value;
public:
    int getValue() const {
        // value = 10; // error: cannot modify non‑static member in const function
        return value;
    }
};

A const member function guarantees that it does not alter any non‑static data members, and only const objects may call it.

2. static keyword: storage and scope control

2.1 static on global variables

// file1.cpp
static int globalStaticVar = 10;
// file2.cpp
// extern int globalStaticVar; // error: cannot access static variable from another file
static

limits the variable’s linkage to the translation unit, avoiding name clashes.

2.2 static on local variables

void count() {
    static int num = 0; // initialized once
    ++num;
    std::cout << "num: " << num << std::endl;
}
int main() {
    count(); // prints 1
    count(); // prints 2
    count(); // prints 3
    return 0;
}

The variable retains its value across function calls because it resides in static storage.

2.3 static on class member variables

class MyClass {
private:
    static int sharedValue;
public:
    MyClass() { ++sharedValue; }
    static int getSharedValue() { return sharedValue; }
};
int MyClass::sharedValue = 0;
int main() {
    MyClass obj1;
    MyClass obj2;
    std::cout << "Shared value: " << MyClass::getSharedValue() << std::endl; // 2
    return 0;
}

All instances share a single copy of sharedValue.

2.4 static on class member functions

class MathUtils {
public:
    static int add(int a, int b) { return a + b; }
};
int main() {
    int result = MathUtils::add(3, 5);
    std::cout << "Result: " << result << std::endl; // 8
    return 0;
}

Static member functions can be invoked without creating an object and can only access other static members.

3. Can const and static be combined?

Yes. A variable declared static const lives for the program’s lifetime and is immutable, making it ideal for shared constants such as configuration parameters.

class MyClass {
public:
    static const int MAX_SIZE = 100;
};

All objects see the same unchangeable value.

3.1 Initialization rules for static const members

For integral types, initialization can occur inside the class definition:

class MathConstants {
public:
    static const int MAX_COUNT = 100;
    static const char DEFAULT_CHAR = 'A';
};

If the address of the constant is taken, a separate definition may be required in a source file.

Non‑integral static const members (e.g., double, std::string) historically required out‑of‑class definitions, but C++11 introduced constexpr for in‑class initialization, and C++17 added inline static for all types.

class MyClass {
public:
    static constexpr double GRAVITY = 9.8; // C++11
    inline static const std::string NAME = "MyClass"; // C++17
};

3.2 Typical use as configuration parameters

class NetworkConfig {
public:
    static const int MAX_CONNECTIONS = 100;
    static const int PORT = 8080;
    static const std::string SERVER_IP = "127.0.0.1";
};

These constants are globally accessible, immutable, and improve code clarity.

4. Frequently asked interview questions

4.1 How many ways can const qualify a pointer?

const int *p

– pointer to constant data; the data cannot be modified, but the pointer can change. int *const p – constant pointer; the pointer cannot change, but the pointed‑to data can be modified. const int *const p – constant pointer to constant data; neither the pointer nor the data can be changed.

4.2 Difference between static local variables and ordinary locals

Static locals reside in static storage, persist for the program’s lifetime, and are initialized only once; ordinary locals are stack‑allocated, recreated on each function entry, and destroyed on exit.

4.3 Difference between static and non‑static class members

Static members belong to the class itself and are shared by all instances, requiring out‑of‑class definition; non‑static members belong to each object instance.

4.4 Effect of const on member functions

Prevents modification of non‑static data members; attempts cause compile‑time errors.

Only const objects can invoke const member functions.

Improves readability by signalling a read‑only operation.

4.5 Can const and static modify the same variable?

Yes. The variable becomes a read‑only static entity, useful for global constants or shared configuration values.

programminginterviewconstC++keywordsstaticlanguage fundamentals
Deepin Linux
Written by

Deepin Linux

Research areas: Windows & Linux platforms, C/C++ backend development, embedded systems and Linux kernel, etc.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.