Type Qualifiers in C++

In C++, type qualifiers are keywords that modify the properties of data types, influencing how variables, pointers, or references can be used. These qualifiers enhance variable declarations by providing additional information on their access and usage constraints, ensuring more controlled and secure code behavior. In C++ common type qualifiers include: const, volatile, and mutable, each serving to specify particular attributes or constraints for handling variables and memory.

const Qualifier in C++

In C++, the const qualifier is used to define constants or variables that cannot be modified after they have been initialized. If we attempt to alter a const variable then it results in a compile-time error. This restriction helps in reducing bugs by preventing unintended modifications to variables and it also allows the compiler to optimize code assuming the values will remain unchanged.

Syntax of const in C++

 const dataType variableName = value ;

Example

The below example demonstrates how we can use const qualifier in C++.

C++
// C++ program to demonstrate the use of const qualifier

#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;

    // The below line will throw an Error: because we are
    // Attempting to modify a const variable num = 50;
    //const  int num =45;
    // cout << "Value of num is: " << num;

    return 0;
}

Output
Value of num is: 50

volatile Qualifier in C++

In C++, the volatile qualifier is used to mark variables that might change unexpectedly, often due to external factors like hardware interactions. This keyword can be applied to variables, as well as to structures and unions to ensure that their member variables are treated as volatile. 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 to its actual memory location, preventing the compiler from caching the variable in registers or removing seemingly redundant accesses.

Syntax of volatile in C++

volatile dataType variableName;

Example

The below example demonstrates how we can use volatile qualifiers in C++.

C++
// C++ program to demonstrate the use of volatile qualifier

#include <chrono>
#include <iostream>
#include <thread>
using namespace std;

// Declaring y as a volatile integer to ensure changes are
// noticed by all threads.
volatile int y = 0;

// Function to change the value of y after a delay.
void changeY()
{
    // Pause the program execution for 1 second.
    this_thread::sleep_for(std::chrono::seconds(1));
    // Change the value of y.
    y = 20;
}

int main()
{
    // Create a new thread that runs the changeY function.
    thread t(changeY);

    // Busy-wait loop that exits when y changes.
    while (y == 0) {
    }

    // Print the updated value of y.
    cout << "Value of y: " << y << endl;

    // Wait for the thread t to finish.
    t.join();

    return 0;
}


Output

Value of y: 20

mutable Qualifier in C++

In C++, the mutable qualifier allows a class member to be modified even when the containing object is declared as const. This is particularly useful for members that do not contribute to the object’s externally visible state. For example, variables used for caching, lazy evaluation, or tracking state internally, where changes do not affect the object’s logical consistency. Unlike the const qualifier, which enforces immutability, mutable enables controlled mutability, allowing for modifications in otherwise immutable contexts.

Syntax of mutable in C++

mutable dataType nameofVariable ; 

Example

The below example demonstrates how we can use mutable qualifier in C++.

C++
// C++ program to demonstrate the use of mutable qualifier

#include <iostream>
using namespace std;

// Define a class named Counter.
class Counter {
private:
    // Declare a mutable integer variable to hold the count.
    mutable int count;

public:
    // Constructor to initialize the count.
    Counter(int initialCount)
        : count(initialCount)
    {
    }

    // Const member function to increment the count.
    void increment() const
    {
        // Increment the count. This is allowed because
        // count is mutable.
        count++;
    }

    // Const member function to get the current count.
    int getCount() const { return count; }
};

int main()
{
    // Create an instance of Counter with an initial count
    // of 5.
    Counter c(5);

    // Print the initial count.
    cout << "Initial Count: " << c.getCount() << endl;

    // Increment the count.
    c.increment();

    // Print the count after incrementing.
    cout << "Count after Incrementing: " << c.getCount()
         << endl;

    return 0;
}

Output
Initial Count: 5
Count after Incrementing: 6

Conclusion

In conclusion, type qualifiers are really useful in many cases. We can use const to make the variable immutable. volatile keyword can be used to indicate that the variable declared with the volatile keyword might change unexpectedly. Also, we have a mutable keyword that allows us flexibility as we can modify the class member even when the containing object is declared as const.



Contact Us