Exploring the Power of ‘const’ in C++

Hey there, future coders! Today, we’re going to explore a magical word in the world of C++ programming: ‘const‘. Don’t worry if you’re just starting out—we’re going to break everything down into bite-sized pieces. Ready to start the adventure? Let’s go!

‘const’—What’s That?

In C++, when we use the keyword ‘const’, it means that the value of a variable cannot be changed. It’s like making a promise that the variable will always have the same value. Once we assign a value to a ‘const’ variable, we can’t change it later. It’s a way to ensure that certain values remain constant and cannot be accidentally modified.

Syntax:

The ‘const’ keyword in C++ is used to indicate that a variable is constant and its value cannot be modified after initialization. The syntax to declare a constant variable using ‘const’ is:

C++
const data_type variable_name = value;

Here, ‘data_type‘ represents the type of the variable (e.g., int, float, char), ‘variable_name‘ is the name of the constant variable, and ‘value‘ is the initial value assigned to the constant variable.

Why Do We Need ‘const’?

Imagine you’re writing a story, and suddenly one of the main characters changes their name halfway through. That would be really confusing! In programming, we want certain values to stay the same, just like the value of pi in math is always 3.14159. By using ‘const’, we can make sure that these values cannot be changed accidentally in our code. It’s like putting a lock on them to prevent any unwanted modifications. This helps us avoid mistakes and ensure that our program behaves correctly.

Exploring the Power of 'const' in C++
How to declare constants

Const Keyword With Pointer Variables

  • Constant Pointer: The pointer itself is constant and cannot be made to point to another variable.
  • Pointer to a Constant: The pointer can be made to point to another variable, but the value it points to cannot be changed.
  • Constant Pointer to a Constant: Both the pointer itself and the value it points to are constant and cannot be changed.

Syntax: 

C++
const data_type* var_name;

Code Example:

C++
#include <iostream>
using namespace std;

int main() {
    int num = 10;
    const int* ptr = # // Pointer to a constant integer

    cout << "Value of num: " << num << endl;
    cout << "Value pointed by ptr: " << *ptr << endl;

    // Uncommenting the line below will result in a compilation error
    // *ptr = 20; // Cannot modify a const int through a pointer

    num = 15; // Modifying the original variable

    cout << "Updated value of num: " << num << endl;
    cout << "Value pointed by ptr after update: " << *ptr << endl;

    return 0;
}

Output:

C++
Value of num: 10
Value pointed by ptr: 10
Updated value of num: 15
Value pointed by ptr after update: 15

Explanation:

  • We declare an integer variable num with a value of 10.
  • We create a pointer ‘ptr‘ and use the ‘const‘ keyword to indicate that it points to a constant integer.
  • The value of ‘num‘ is printed, showing its initial value of 10.
  • The value pointed to by ‘ptr‘ (which is also 10) is printed.
  • Trying to modify the value pointed to by ‘ptr‘ Using ‘*ptr = 20‘ will result in a compilation error because the pointer is const.
  • We update the value of the original variable ‘num‘ to 15.
  • The updated value of ‘num‘ is printed as 15.
  • The value pointed to by ‘ptr‘ is still 15, even though it’s a constant pointer.

Constant Methods

Just like how we can mark functions as “const” to prevent them from modifying the object they are called on, we can also declare objects as “const” in a class. When an object is declared as “const,” it means we can’t change its values. Because of this, we can only call functions within the class that are also marked as “const” to ensure they won’t change the object’s values. This helps to keep the object’s data safe and consistent.

Syntax:

C++
const Class_Name Object_name;

There are two ways of a Constant Function declaration:

Ordinary const-function Declaration:

C++
const void foo()
{
   //void foo() const Not valid
}                  
int main()
{
   foo();
}  

A const member function of the class:

C++
class
{
   void foo() const
   {
       //.....
   }
}

Code Example of Constant Function:

C++
#include <iostream>
using namespace std;

class Circle {
private:
    double radius;

public:
    Circle(double r) {
        radius = r;
    }

    // Constant member function to calculate the area
    double calculateArea() const {
        return 3.14159 * radius * radius;
    }
};

int main() {
    Circle circle(5.0);

    // Calling the constant member function
    double area = circle.calculateArea();

    cout << "Area of the circle: " << area << endl;

    return 0;
}

Output:

C++
Area of the circle: 78.5398

Explanation:

  • The example includes a function named calculateArea().
  • The function is marked as constant using the const keyword.
  • A constant member function doesn’t change any class variables.
  • It can be used with both constant and non-constant objects of the class.

Real Life Example of Const

Theory:

In C++, the keyword const stands for “constant”. It’s used to declare variables whose values should not change after they’re set. Once a ‘const‘ variable is assigned a value, you can’t modify that value later in the code. It’s a way of telling the compiler, “Hey, this value should remain the same and if I mistakenly try to change it, please give me an error.”

Real-life analogy:

Think of a ‘const‘ variable like a sealed time capsule. Once you’ve filled it and sealed it, you can’t open it up again to change its contents. It’s going to remain the same forever (or until it’s opened by someone in the future, but in our analogy, we’ll say it remains sealed forever).

Example in context:

Imagine you’re starting a new job and you’re given a permanent employee ID on your first day. This ID is unique to you and won’t change for the entire time you’re at the company. It’s like your constant identifier. So, if we were to represent this scenario in C++:

C++
const int employeeID = 12345;  // This ID is set once and can't be modified later.

If later in the program you mistakenly try to change your employeeID like this:

C++
employeeID = 67890;  // This will throw a compiler error because employeeID is declared as const.

The compiler will alert you with an error, ensuring that the value remains consistent and unaltered throughout your program.

Problem Statement and Uses

Problem Statement:

Imagine you are working for a company that produces and sells luxury wristwatches. Each model of the watch has a unique model number, and once this model number is assigned, it should never change. Additionally, each watch model has a fixed production year, which also remains constant.

Your task is to design a simple C++ program to store and display information about different watch models using the concept of ‘const‘ to ensure that the model number and production year of each watch remains immutable.

Requirements:

  1. Create a class named ‘Watch‘.
  2. The class should have two ‘const‘ member variables: modelNumber and ‘productionYear‘.
  3. Write a constructor for the ‘Watch‘ class that initializes these two const variables.
  4. Write a method named ‘displayInfo()‘ to print out the model number and production year of the watch.
  5. In the ‘main()‘ function, create a few watch objects with different model numbers and production years, and display their information.

Constraints:

  1. Ensure that once a watch object is created, its model number and production year can’t be changed.
  2. If you try to modify these ‘const‘ values after initialization, your code should generate a compile-time error.

Hint:

  • You might need to use member initializer lists in your constructor to initialize the const member variables.

Expected Output:

For a watch object initialized with model number 101 and production year 2022, the output should be something like:

C++
Model Number: 101
Production Year: 2022

Examples to understand ‘const

Let’s look at some examples to understand ‘const‘ better. We’ll start with a simple example and gradually add more complexity.

Example 1: Basic ‘const’ Variable

C++
#include <iostream>
using namespace std;

int main() {
    const int maxPlayers = 10;
    cout << "Max players: " << maxPlayers << endl;
    return 0;
}

Output:

C++
Max players: 10

Explanation:

  • The variable ‘maxPlayers’ is declared as ‘const’.
  • It’s assigned the value 10 during initialization.
  • Once assigned, the value of ‘maxPlayers’ cannot be changed.

Example 2: ‘const’ with Arrays

C++
#include <iostream>
using namespace std;

int main() {
    const int arraySize = 5;
    int myArray[arraySize] = {1, 2, 3, 4, 5};
    for (int i

= 0; i < arraySize; i++) {
        cout << myArray[i] << " ";
    }
    return 0;
}

Output:

C++
1 2 3 4 5

Explanation:

  • ‘arraySize’ is declared as a ‘const’ variable.
  • It is used to define the size of the ‘myArray’ array.
  • This const declaration ensures that the size of ‘myArray’ remains fixed.
  • It prevents accidental changes to the array size.

Example 3: ‘const’ with Functions

C++
#include <iostream>
using namespace std;

double circleArea(const double radius) {
    const double pi = 3.14159;
    return pi * radius * radius;
}

int main() {
    double radius = 5.0;
    cout << "Area: " << circleArea(radius) << endl;
    return 0;
}

Output:

C++
Area: 78.53975

Explanation:

  • In the example, there’s a const variable named ‘pi‘ declared inside the ‘circleArea‘ function.
  • Even though ‘pi‘ is a local variable, marking it as ‘const‘ ensures that its value remains constant and cannot be changed.
  • This helps prevent accidental modifications to the value of ‘pi‘ within the function.
  • By using ‘const‘, you signal to the compiler and other programmers that the variable should not be modified once it’s assigned a value.
  • This is especially useful for variables like mathematical constants that are expected to maintain a fixed value throughout the function’s scope.

Example 4: ‘const’ with Pointers

C++
#include <iostream>
using namespace std;

int main() {
    int x = 10;
    const int* p = &x;
    //*p = 20;  // This will cause a compile error
    cout << "*p: " << *p << endl;
    return 0;
}

Output:

C++
*p: 10

Explanation:

  • In the given example, we have a pointer named ‘p’.
  • ‘p’ is a pointer to a constant integer, denoted as const int.
  • This implies that using ‘p’ to modify the value of the integer ‘x’ is not allowed.

Example 5: ‘const’ with Classes and Multiple Inheritance

C++
#include <iostream>
using namespace std;

class Base1 {
public:
    static const int x = 10;
};

class Base2 {
public:
    static const int y = 20;
};

class Derived : public Base1, public Base2 {};

int main() {
    cout << "x = " << Derived::x << ", y = " << Derived::y << endl;
    return 0;
}

Output:

C++
x = 10, y = 20

Explanation:

  • The example involves three classes: ‘Derived‘, ‘Base1‘, and ‘Base2‘.
  • Derived‘ is a class that inherits from both ‘Base1‘ and ‘Base2‘.
  • It inherits the ‘const‘ members ‘x‘ from ‘Base1‘ and ‘y‘ from ‘Base2‘.

Advantages and Disadvantages of ‘const’

Advantages of ‘const’Disadvantages of ‘const’
Ensures data integrityCan be restrictive if used excessively
Provides self-documenting codeRequires careful initialization
Helps prevent accidental modificationsRequires understanding of const correctness
Enables compiler optimizationsMay add complexity to code
Supports immutability and safetyCan increase code verbosity
Enhances code readabilityMay require additional type qualifiers
The Good and the Not-So-Good of ‘const’

Key Takeaways

  • Constant Declarations: The ‘const‘ keyword in C++ is used to declare constants, which are values that cannot be changed after they are assigned.
  • Immutable Variables: When a variable is declared with ‘const‘, its value becomes immutable, preventing accidental modifications in the code.
  • Safer Code: Using ‘const‘ ensures that variables intended to remain constant do not accidentally change during program execution, leading to more reliable code.
  • Code Readability: By indicating that a variable is constant, the code becomes more readable and self-explanatory, making it easier for others (and yourself) to understand the intended behavior.
  • Compiler Optimization: The use of ‘const‘ can aid the compiler in making optimizations, potentially resulting in more efficient code.
  • Applicability: The ‘const‘ keyword can be used with various entities, including variables, pointers, member functions, and more.
  • Important Skill: Understanding and effectively using const is essential for both beginners and experienced programmers in C++, contributing to better code quality and maintainability.

Conclusion

In this article, we’ve explored the magic of const in C++. We’ve learned what it is, why it’s needed, and how it’s used. We’ve also looked at some real-life scenarios, explored the concept of multiple inheritance, and worked through several examples. Whether you’re a beginner just starting out or an experienced programmer looking to brush up on your skills, understanding ‘const‘ is a crucial step in mastering C++.

Frequently Asked Questions

1. What is ‘const’ in C++?

In C++, const is a keyword that you can use to declare a constant. A constant is a variable whose value cannot be changed after it’s been initialized.

2. Why is ‘const’ needed in C++?

const is needed when you want to have data that should not be changed. By declaring a variable as const, you can ensure that its value remains constant throughout the program.

3. How is ‘const’ used in C++?

You can declare a variable as const by placing the const keyword before the variable’s type in its declaration. Once a const variable has been initialized, its value cannot be changed.

4. What is multiple inheritance in C++?

Multiple inheritance is a feature of C++ that allows a class to inherit from more than one class. This means that a class can use the member functions (and other members) of multiple other classes.

5. What are the advantages and disadvantages of ‘const’ in C++?

Advantages of const include safety (preventing accidental changes to variables), readability (making it clear which variables are constants), and potential efficiency (some compilers can optimize const variables). Disadvantages can include reduced flexibility (once a const variable has been initialized, its value can’t be changed) and increased complexity (the rules for const can be complex, especially when dealing with pointers and references).

Deepak Vishwakarma

Founder

RELATED Articles

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.