Open In App

Type Qualifiers in C++

Last Updated : 26 Oct, 2025
Comments
Improve
Suggest changes
1 Likes
Like
Report

Type qualifiers are keywords that modify the properties of data types, influencing how variables, pointers, or references can be used.

  • They specify how a variable can be used or modified, making the program safer and more controlled.
  • Common type qualifiers in C++ include const, volatile, and mutable.

const Qualifier in C++

  • const keyword is used to make variables constant, meaning their value cannot be changed after initialization.
  • If you try to modify a const variable, the compiler gives an error.
  • It helps to avoid accidental changes to important values in the program and helps the compiler optimize the code since it knows the value won't change.
  • You can use const with variables, pointers, function parameters, and class methods to make them unchangeable.
C++
#include <iostream>
using namespace std;

int main()
{
    // define a const variable num
    const int num = 50;
    
    // print the value of num
    cout << "Value of num is: " << num;


    return 0;
}

Output
Value of num is: 50

Note : If we try to modify the value of a const variable, the compiler will generate an error.

volatile Qualifier in C++

  • volatile marks a variable whose value can change unexpectedly outside the normal program flow.
  • When we declare a variable as volatile, the compiler is instructed not to optimize code involving this variable to ensure that every access to the variable is directly from its actual memory location, preventing the compiler from caching the variable in registers.
  • Every access to a volatile variable is done directly from memory, ensuring the program always sees the latest value.
  • It is commonly used for hardware registers, interrupts, or shared variables in multithreading.
C++
#include <iostream>
using namespace std;

int main()
{
    // Declare a volatile variable
    volatile int value = 0;

    cout << "Initial value: " << value << endl;

    // Simulate an unexpected change
    value = 10; 
    cout << "Updated value: " << value << endl;

    return 0;
}

Output
Initial value: 0
Updated value: 10

mutable Qualifier in C++

  • mutable allows a class member to be changed even if the object is declared as const.
  • It is useful for internal data that doesn’t affect the object’s main behavior, like counters, caches, or temporary calculations.
  • This lets you update some parts of an object while keeping the rest of it read-only.
  • mutable can only be used with non-static class members.
C++
#include <iostream>
using namespace std;

class Counter
{
  public:
    mutable int count = 0;

    void increment() const
    {
        count++;
    }
};

int main()
{
    const Counter c;
    cout << "Initial Count: " << c.count << endl;

    c.increment();
    cout << "Count after increment: " << c.count << endl;

    return 0;
}

Output
Initial Count: 0
Count after increment: 1

Explore