Welcome to our comprehensive guide on const correctness in C++! This tutorial is designed for both beginners and intermediates, so let's dive right in! š³
const šIn C++, const is a keyword used to declare variables as constant. A const variable cannot be modified after its initial assignment.
int a = 10; // A regular variable
const int b = 20; // A const variable
a = 20; // This is valid
b = 30; // This is not validš” Pro Tip: Using const can help prevent accidental modifications and improve code readability.
C++ offers various const qualifiers to make our code more robust and efficient.
A const function member is a function that does not modify any non-const data members of the object it is called upon.
class MyClass {
int data;
public:
MyClass(int d) : data(d) {}
int getData() const {
return data; // This is a const function
}
void setData(int d) {
data = d; // This is a non-const function
}
};
int main() {
const MyClass obj(10); // Creating a const object
obj.setData(20); // This will result in a compile-time error
cout << obj.getData(); // This is valid
}A constexpr is a type of constant expression that can be evaluated at compile time. This can lead to increased performance in certain cases.
constexpr int a = 10; // A constexpr variable
int main() {
int b = a + 5; // The value of a is known at compile time, so b can be calculated at compile time
}What is the output of the following code?