Tags
c++
Asked 3 years ago
30 Jul 2021
Views 433
Santiago

Santiago posted

Is string immutable in C++ ?

Is string immutable in C++ ?
dilip

dilip
answered May 2 '23 00:00

In C++, string objects are typically implemented as mutable objects , which means that you can modify the contents of a string object after it has been created . However, C++ also provides a const qualifier that can be used to make a string object immutable, which means that its contents cannot be changed.

When you create a string object in C++, the contents of the string are stored in memory as a sequence of characters, typically terminated by a null character ('\0'). You can access and modify individual characters in the string using indexing or iterators, and you can also use various member functions to manipulate the contents of the string.

For example, here's a simple C++ program that demonstrates how to create and manipulate a string object:


#include <iostream>
#include <string>

int main() {
    std::string str = "hello, world!";

    std::cout << "Original string: " << str << std::endl;

    // Modify the string
    str[0] = 'H';
    str.erase(5, 1);

    std::cout << "Modified string: " << str << std::endl;

    return 0;
}

In this program, a string object is created using the std::string class, and its contents are modified using the indexing operator ([]) and the erase() member function. The output of the program shows the original and modified string.

However, if you declare a string object as const, then you cannot modify its contents:

const std::string str = "hello, world!";


// This line will cause a compiler error
str[0] = 'H';

In this case, the attempt to modify the first character of the string will result in a compiler error, because the str object is declared as const.

So, while string objects in C++ are typically mutable, you can make them immutable by declaring them as const.
Post Answer