Table of contents
1.
Introduction
2.
Using Const Keywords in C++
2.1.
Declare a Variable as a Constant
2.2.
Declare a Pointer to a Constant
2.3.
Constant Arguments
2.4.
Constant Member Functions
3.
Understanding Const Keyword with Example
3.1.
Code
4.
C++
4.1.
Output
4.2.
Explanation
5.
Frequently Asked Questions
5.1.
Why should I use const in C++?
5.2.
What is the const keyword in C#?
5.3.
How to declare constants?
6.
Conclusion
Last Updated: Aug 7, 2024

Const keyword in C++

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Overloading is the ability to use a single identifier to define more than one class method that differs from one another in terms of their input/output parameters. In case of overloading, a method is chosen at the compile time. Function overloading is when two or more functions are defined using the same name but differ from each other in terms of type or number of parameters.
Const is a keyword which when attached to any method, variable, or with the object of a class, will prevent that specific object/method/variable from modifying its data items value. A variable which is declared as a const cannot be left un-initialized at the time of the assignment. In this blog, we will discuss how function overloading and const keyword work together in C++.

Const keyword in C++

Using Const Keywords in C++

The const keyword in C++ is used to indicate that a variable, pointer, argument, or member function is constant, meaning its value or behavior cannot be changed after initialization.

Declare a Variable as a Constant

When a variable is declared as const, its value cannot be modified throughout the program. It provides compile-time protection against accidental modifications.

#include <iostream>
int main() {
   const int x = 5; // Declaring x as a constant
   // x = 10; // Error: Attempting to modify a const variable
   std::cout << "Value of x: " << x << std::endl;
   return 0;
}

Declare a Pointer to a Constant

Declaring a pointer as const means the pointer itself cannot be reassigned to point to a different memory location, whereas declaring the pointed-to value as const ensures that the value it points to cannot be modified.

#include <iostream>
int main() {
   int y = 10;
   const int *ptr = &y; // Pointer to a constant integer
   // *ptr = 20; // Error: Attempting to modify a constant value
   std::cout << "Value pointed by ptr: " << *ptr << std::endl;
   return 0;
}

Constant Arguments

Using const in function parameters ensures that the arguments passed to the function cannot be modified within the function's body, providing both readability and safety.

#include <iostream>
void printValue(const int value) { // Using const in function parameter
   // value = 20; // Error: Attempting to modify a constant parameter
   std::cout << "Value: " << value << std::endl;
}
int main() {
   int num = 15;
   printValue(num);
   return 0;
}

Constant Member Functions

Declaring member functions as const promises that they won't modify the state of the object they're called on. This allows these functions to be called on const objects and ensures logical constancy.

#include <iostream>
class MyClass {
public:
   void printValue() const { // Constant member function
       // memberVar = 20; // Error: Cannot modify member variables in a const member function
       std::cout << "Value: " << memberVar << std::endl;
   }
private:
   int memberVar = 10;
};
int main() {
   const MyClass obj; // Creating a const object
   obj.printValue();
   return 0;
}

Understanding Const Keyword with Example

Code

  • C++

C++

#include<iostream>
using namespace std;

class overload
{
 protected:
 int x;
 public:
 // constructor
overload (int i):x(i) { }

 // Method functions
 void print() const
{
 cout << "-----From inside the Const function-----" << endl;
}
 void print()
{
 cout << "-----From inside the non-const function-----" << endl;
}
};

int main()
{
overload obj1 (300);
 const overload obj2 (130);
obj1.print();
obj2.print();
 return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

-----From inside the non-const function-----
-----From inside the Const function-----


Explanation

In the above code, there are two method functions: void print() const and void print(). The only difference between these two is that one is const and another is not. It can be observed from the output that the method function ‘void print() const’ is called from the const object, and the method function ‘void print()’ is called from the non-const object.

This happens because C++ allows member methods to be overloaded on the basis of const type. This is very useful when a function returns a reference or a pointer. In such a scenario, we can make one function as const, which will return a const reference or a const pointer, whereas the other non-const function will return a non-const reference or pointer.

Frequently Asked Questions

Why should I use const in C++?

Using const in C++ promotes code safety by preventing unintentional modifications to variables, pointers, function parameters, and member functions. It enhances readability and helps enforce logical constancy in programs.

What is the const keyword in C#?

In C#, the const keyword is used to declare constants, which are values that cannot be changed during program execution. These values are determined at compile-time and remain constant throughout the program's execution.

How to declare constants?

In C++, constants can be declared using the const keyword followed by the data type and variable name, optionally initialized with a value. Alternatively, #define can be used for symbolic constants. Constants declared with const provide type safety and are preferred over macros for constants.

Conclusion

In this article, we have extensively discussed the const keyword in C++ programming language.

After reading about the Function Overloading with the const keyword, are you not feeling excited to read/explore more articles on keywords? Don't worry; Coding Ninjas has you covered. 

If you wish to enhance your skills in Data Structures and AlgorithmsCompetitive ProgrammingJavaScript, and many more, then you should check out our Guided path column.

Do upvote if you find the blogs helpful.

Live masterclass