Updated May 11, 2023
Intro to Const Keyword in C++
In C++, the const keyword is used to declare a variable or function parameter as read-only, indicating that its value cannot be modified after initialization. Once a value is assigned to a const variable, it cannot be changed, and any attempt to modify it will result in a compilation error. Const can be used with built-in data types, user-defined types, and functions. It is also helpful for defining constant expressions, improving code safety, and enabling compiler optimizations. By preventing accidental modifications of variables, const helps developers to write more robust and reliable code.
Key Takeaways
- Const can be used with pointers to specify that the value pointed by the pointer is read-only.
- Const member functions can be used to ensure that a member function does not modify the object it is called on.
- Const is used in function signatures to indicate that a function will not modify its parameters.
- Const can also be used with references, allowing you to create read-only references to data.
- Const helps to improve performance by allowing the compiler to make certain optimizations.
What is Const Keyword in C++?
- In C++, the const keyword is a fundamental concept that specifies that a variable or function parameter is read-only and cannot be modified. It is a crucial tool for ensuring the correctness and safety of C++ code by preventing accidental modifications to important values.
- Const helps define constant expressions and enable compiler optimizations. It can be used with built-in data types, user-defined types, and functions.
- By declaring variables const, developers can write more robust, reliable, and efficient code. Additionally, const member functions and references can provide further guarantees about the immutability of objects and their associated data.
- Overall, the const keyword is a powerful and versatile tool in the C++ language that enables developers to write safer, more efficient, and more reliable code.
Const Keywords in C++ with Different Parameters
1. Using Const Variable
A const variable in C++ is a read-only variable whose value cannot be changed once it has been defined. It is declared using the const keyword before the variable type. Once a value is assigned to a const variable, It can’t be modified, and any attempt to change it will result in a compilation error.
Here’s an example of how to use a const variable in C++.
Code:
#include
int main() {
const int MAX_VALUE = 100;
int value;
std::cout << "Enter a value between 1 and " << MAX_VALUE << ": "; std::cin >> value;
if (value > MAX_VALUE) {
std::cout << "Error: value too large" << std::endl;
return 1;
}
std::cout << "The value you entered is " << value << std::endl;
return 0;
}
Output:
Explanation: In this example, a const integer variable named MAX_VALUE is declared and assigned a value of 100. This variable validates user input by ensuring that the value entered by the user is not greater than MAX_VALUE. Since MAX_VALUE is declared const, it cannot be modified later in the program.
2. Using Const with Pointers
In C++, the const keyword is enabled with pointers to create read-only pointers. When a pointer is declared as const, The const pointer cannot change its address after it is initialized; therefore, once it is initialized as a const pointer, it will always point to the same address. Const is placed before the pointer type to declare it.
Here’s an example of how to use const with pointers in C++:
Code:
#include
int main() {
int value = 10;
const int* ptr = &value;
std::cout << "The value is " << *ptr << std::endl;
value = 20; // This is allowed because the value is not const
// *ptr = 30; // This is not allowed because ptr is a const pointer
const int* const const_ptr = &value;
// const_ptr = nullptr; // This is not allowed because const_ptr is a const pointer
// *const_ptr = 30; // This is not allowed because const_ptr points to a const value
return 0;
}
Output:
A non-const integer variable named value is declared and initialized with a value of 10. A pointer named ptr is expressed as a const pointer to an integer, which is initialized to point to a value. Since ptr is a const pointer, we cannot use it to modify the value.
Then, a const pointer to an integer named const_ptr is declared and initialized to point to the value. Since both the pointer and the pointed-to value is const, neither can be modified.
3. Using Pointer to Const Variables
A const pointer in C++ is a pointer to a memory location whose value cannot be modified by using the pointer to access it. A read-only reference to a variable can be created using a const pointer. Here’s an example:
Code:
#include
int main() {
int value = 10;
const int* ptr = &value;
std::cout << "The value is " << *ptr << std::endl;
// *ptr = 20; // This is not allowed because ptr is a const pointer
value = 20;
std::cout << "The value is " << *ptr << std::endl;
return 0;
}
Output:
Explanation: In this example, an integer variable named value is declared and initialized with a value of 10. A const pointer named ptr is then declared and assigned to the address of the value. Since ptr is a const pointer, the value of value cannot be changed through ptr.
The value of value is printed to the console using the * operator to dereference ptr. Attempting to modify the value of value through ptr using the assignment operator would result in a compile error. The value of value is then changed to 20, and the value of *ptr is printed to the console again. Since ptr is a const pointer, the value of *ptr remains unchanged and continues to be 10.
4. Using Const with Function Arguments
In C++, the const keyword can be used with function arguments to indicate that a function does not modify the value of the argument. When a function argument is declared as const, it cannot be changed within the function. This helps to prevent unintentional modification of important data and improves the safety and reliability of C++ code.
Here’s an example of how to use const with function arguments in C++:
Code:
#include
void print_value(const int& value) {
// value = 20; // This is not allowed because value is a const reference
std::cout << "The value is " << value << std::endl;
}
int main() {
int value = 10;
print_value(value);
return 0;
}
Output:
Explanation: In this example, a function named print_value is defined to take a const reference to an integer as its argument. Since the argument is declared as const, cannot modify within the function. The function simply prints the value of the argument to the console.
In the main, an integer variable named value is declared and initialized with a value of 10. print_value is then called with value as its argument. Since the argument is passed as a const reference, it cannot be modified within the function, ensuring that the value of value remains unchanged.
5. Using Const with Class Member Functions
In C++, the const keyword can be used with class member functions to indicate that the function does not modify the object’s state. A const member function can be used on a const object, but it is not permitted to change any of the class’ non-static data members.
Here’s an example of how to use const with class member functions in C++:
Code:
#include
class MyClass {
public:
void set_value(int value) {
m_value = value;
}
int get_value() const {
return m_value;
}
private:
int m_value = 0;
};
int main() {
const MyClass my_object;
// my_object.set_value(10); // This is not allowed because my_object is const
std::cout << "The value is " << my_object.get_value() << std::endl;
return 0;
}
Output:
Explanation: In this example, a class named MyClass is defined with two member functions: set_value, which sets the value of a private member variable m_value, and get_value, which returns the value of m_value. The get_value function is declared as const, indicating that it does not modify the object’s state.
In main, a const object of the class MyClass is created. Since my_object is const, the set_value function cannot be called on it. However, the get_value function can be called on my_object to retrieve the value of m_value.
6. Using Const with Class Data Members
In C++, the const keyword can be used with class data members to indicate that their values cannot be changed after initializing them nor during its declaration but can assign the constructor values. This can be useful for creating read-only data members that are guaranteed to have a constant value throughout the lifetime of an object. Here’s an example:
Code:
#include
class MyClass {
public:
MyClass(int value) : m_value(value) {}
int get_value() const {
return m_value;
}
private:
const int m_value;
};
int main() {
const MyClass my_object(10);
// my_object.m_value = 20; // This is not allowed because m_value is const
std::cout << "The value is " << my_object.get_value() << std::endl;
return 0;
}
Output:
Explanation: In this example, a class named MyClass is defined with a const integer data member named m_value. The class also includes a constructor that takes an integer value and initializes m_value with it, and a const member function named get_value that returns the value of m_value.
In main, a const object of the class MyClass is created and initialized with a value of 10. Since my_object is const, the value of m_value cannot be changed after it has been initialized. Attempting to modify the value of m_value using the dot notation would result in a compile error.
The value of m_value is printed to the console using the get_value member function. Since m_value is const, the value returned by get_value is guaranteed to be the same throughout the lifetime of my_object.
7. Using Const with Class Objects
In C++, the const keyword can be used with class objects to indicate that the object is immutable and cannot be modified. This can be useful to ensure that the object’s state is maintained throughout its lifetime and can improve the safety and reliability of C++ code. Here’s an example:
Code:
#include
class MyClass {
public:
MyClass(int value) : m_value(value) {}
int get_value() const {
return m_value;
}
void set_value(int value) {
m_value = value;
}
private:
int m_value;
};
int main() {
const MyClass my_object(10);
// my_object.set_value(20); // This is not allowed because my_object is const
std::cout << "The value is " << my_object.get_value() << std::endl;
return 0;
}
Output:
Explanation: In this example, a class named MyClass is defined with an integer data member named m_value, a constructor that takes an integer value and initializes m_value with it, and two member functions: get_value, which returns the value of m_value and set_value, which sets the value of m_value.
In main, a const object of the class MyClass is created and initialized with a value of 10. Since my_object is const, the set_value member function cannot be called on it, as this would attempt to modify the object’s state. The value of m_value is printed to the console using the get_value member function. Since my_object is const, the value returned by get_value is guaranteed to be the same throughout the lifetime of my_object.
Conclusion
In C++, the const keyword can be used with variables, pointers, function arguments, class data members, and class objects to indicate that their values or state cannot be modified. This improves the safety and reliability of C++ code by preventing inadvertent modification of important data.
Recommended Article
We hope that this EDUCBA information on “Const keyword in C++” was beneficial to you. You can view EDUCBA’s recommended articles for more information.