Constant Arguments in C++
Constant Arguments:
- A function's parameter can be defined as a constant in C++. When a function is given the qualifier Constant, the compiler is informed that the parameter should not be changed.
- When this condition is not met, the compiler will produce an error. Only when we give arguments by reference or pointers is this form of declaration significant.
- One whose modification by the function is prohibited is referred to as a constant argument. The term Constant can also be used, for example, in the expression int sum (const int a, const b), to make an argument to a function constant.
- The function prototype's qualifier const further informs the compiler that the function cannot change the parameter.
- It is possible to declare a function to be const by using the keyword const in the function declaration. It is not intended for constant functions to be able to alter the object on which they are called.
- The method of making as many functions const should be implemented in order to prevent unexpected changes to objects.
Syntax for the Declaration of Constant Arguments in C++:
int strlen(const char *p);
int length(const string &s);
How to Use Constant Keywords in C++?
- Pointers can be used with const to indicate that the value they point to is read-only.
- To ensure that a member function does not alter the object it is called on, const member functions can be used.
- Const is a keyword used in function signatures to denote a function's inability to change its input parameters.
- Const can be used in combination with references to establish read-only references to data.
- By enabling specific compiler optimisations, Const aids in performance improvement.
Different Cases of implementing Const Keyword in C++:
1. Implementing a Const Variable:
- When a variable is defined in C++, it becomes a read-only, immutable const variable. Const comes before the variable type when it is declared.
- A compilation error will be produced if an attempt is made to change a value that has been assigned to a const variable since once it has been set, it cannot be modified.
- The use of a const variable in C++ is demonstrated here:
#include <iostream>
int main() {
const int MAX = 10;
int n;
std::cout << "Select a number between 1 and " << MAX << ": "; std::cin >> n;
if (n > MAX)
{
std::cout << "error: Value is too large," << std::endl;
return 1;
}
std::cout << "Your entered value is " << n << std::endl;
return 0;
}
OUTPUT:
![CONSTANT ARGUMENTS IN C++](https://static.tutorialandexample.com/cpp/constant-arguments-in-cpp1.png)
Explanation:
- This example declares and gives the value 10 to a const integer variable called MAX. The value given by the user must not exceed MAX in order for this variable to validate user input.
- MAX cannot be changed later in the program since it is const because it has been defined that way.
2. Creating Pointers using Const Keyword:
- The const keyword with pointers in C++ allows for the creation of read-only pointers.
- A pointer that has been initialised as a const pointer will always point to the same address since a pointer that has been declared const cannot change its address after initialization.
- To declare a pointer type, const is added before the type.
- Here is an illustration of using const with pointers in C++:
#include <iostream>
int main() {
int n = 10;
const int* ptr = &n;
std::cout << "The value which is given " << *ptr << std::endl;
n = 10; // As the value is not const, this is acceptable.
// *ptr = 20; // Because ptr is a const pointer, this is not acceptable.
const int* const cons_ptr = &n;
// cons_ptr = nullptr; // Because const_ptr is a const pointer, this is not acceptable.
// *cons_ptr = 20; // Because const_ptr points to a const, this is not acceptable.
return 0;
}
OUTPUT:
![CONSTANT ARGUMENTS IN C++](https://static.tutorialandexample.com/cpp/constant-arguments-in-cpp2.png)
Explanation:
- Value is declared as a non-const integer variable, and its initial value is set to 10. The name "ptr" pointer is expressed as a const pointer to an integer initialised to point to a value.
- We are unable to change the value using ptr because it is a const pointer.
- The value is then pointed to by initialising a const pointer to an integer named cons_ptr. Since the pointed-to value and the pointer are both const, neither can be altered.
3. Utilising Const Pointer Variables:
In C++, a pointer to a memory place is known as a const pointer if using the pointer to access it results in the value of the memory location being immutable. Const pointers allow the creation of read-only references to variables.
Here is an illustration:
#include <iostream>
int main() {
int n = 100;
const int* ptr = &n;
std::cout << "The value which is given " << *ptr << std::endl;
// *ptr = 20; // Because ptr is a const pointer, this is not acceptable.
n = 200;
std::cout << "The value which is given " << *ptr << std::endl;
return 0;
}
OUTPUT:
![CONSTANT ARGUMENTS IN C++](https://static.tutorialandexample.com/cpp/constant-arguments-in-cpp3.png)
Explanation:
- An integer variable called value is declared in this example and given the initial value of 100.
- The value's address is then specified, and ptr is a const pointer that is assigned to it. The value of value cannot be altered by using ptr because it is a const pointer.
- The * operator is used to dereference ptr and print the value of value to the console. Using the assignment operator to modify the value of value through ptr would result in a build error.
- Next, value is set to 200, and *ptr's value is once more written to the console. The value of *ptr stays constant and is still 100 because ptr is a const pointer.
4. Applying Const with Arguments from Functions:
- With function arguments in C++, the const keyword can be used to provide that a function doesn't change the value of the parameter.
- When a function argument has been assigned as const, the function cannot be altered while using that argument. As a result, the security and dependability of C++ programming are increased and unintended modification of crucial data is prevented.
- Here is a C++ example of using const with function arguments:
#include <iostream>
void print(const int& n)
{
// n = 30; // Value is a const reference, hence this is not acceptable.
std::cout << "The value which is given " << n << std::endl;
}
int main()
{
int n = 10;
print(n);
return 0;
}
OUTPUT:
![CONSTANT ARGUMENTS IN C++](https://static.tutorialandexample.com/cpp/constant-arguments-in-cpp4.png)
Explanation:
- A const reference to an integer is used as the argument for the function print, which is defined in this example. The function cannot be modified because the argument is specified as const.
- Printing the argument's value to the console is all that the function does.
- ‘n’ is a declared integer variable that has a value of 10 initialised to it in the main. Then value, the parameter to print, is invoked.
- The value of ‘n’ is guaranteed to remain unchanged because the argument is supplied as a const reference, which cannot be changed inside the function.
5. Making Use of Const in Class Member Functions:
- When class member functions are used in C++, the const keyword can be used to signal that the function doesn't change the state of the object.
- On a const object, a const member function may be invoked, but it is not allowed to modify any of the class' non-static data members.
- Here is an illustration of how to utilise C++'s const operator with class member functions:
#include <iostream>
class My_Class
{
public:
void set_val(int val) {
my_val = val;
}
int get_val() const {
return my_val;
}
private:
int my_val = 10;
};
int main()
{
const My_Class My_Obj;
// My_Obj.set_val(10); // My_Obj is const, hence this is not accepted.
std::cout << "The value which is given " << My_Obj.get_val() << std::endl;
return 0;
}:
OUTPUT:
![CONSTANT ARGUMENTS IN C++](https://static.tutorialandexample.com/cpp/constant-arguments-in-cpp5.png)
Explanation:
- In this illustration, a class called My_Class is defined with two member functions: set_val, which modifies the value of a private member variable called my_val, and get_val, which retrieves my_val's value.
- The const keyword in the get_val function's declaration means it won't change the object's state.
- The class My_Class const object is formed in the main function. It is not possible to call the set_val function on My_Obj since it is const. The value of my_val can be retrieved by using the get_val method on My_Obj, too.
6. Using Class Data Members with Const:
- The const keyword in C++ can be used to specify that a class's data members' values cannot be modified after initialization or during declaration, but that the constructor can set their values.
- This can be helpful to establish read-only data members with constant values throughout every phase of an object's existence.
Here's an example:
#include <iostream>
class My_Class
{
public:
My_Class(int val) : my_val(val) {}
int get_val() const
{
return my_val;
}
private:
const int my_val;
};
int main()
{
const My_Class My_Obj(10);
// My_obj.my_val = 20; // my_val is const, hence this is not accepted.
std::cout << "The value is " << My_Obj.get_val() << std::endl;
return 0;
}
OUTPUT:
![CONSTANT ARGUMENTS IN C++](https://static.tutorialandexample.com/cpp/constant-arguments-in-cpp6.png)
Explanation:
- The data member my_val is a const integer that is used to define the class My_Class in this example.
- Additionally, the class has a get_val const member method that returns the value of my_val and a constructor that accepts an integer value to initialise my_val with.
- The class My_Class const object is formed and given the initial value of 10 in the main function.
- My_val cannot be altered once it has been initialised because My_obj is const and cannot be changed. Dot notation would cause a compile error if you tried to change the value of my_val.
7. Implementing Const for Class Objects:
- Class objects in C++ can be immutable and cannot be changed by using the const keyword to express this. This can help to keep the object's state over the span of its existence and increase the reliability and security of C++ programming.
- Here's an illustration:
#include <iostream>
class My_Class
{
public:
My_Class(int val) : my_val(val) {}
int get_val() const
{
return my_val;
}
void set_value(int val)
{
my_val = val;
}
private:
int my_val;
};
int main()
{
const My_Class My_Obj(10);
// My_obj.set_val(20); // My_Obj is const, hence this is not accepted.
std::cout << "The value is " << My_Obj.get_val() << std::endl;
return 0;
}
OUTPUT:
![CONSTANT ARGUMENTS IN C++](https://static.tutorialandexample.com/cpp/constant-arguments-in-cpp7.png)
Explanation:
- In this example, a class called My_Class has been defined with an integer data member named my_val, a constructor that accepts an integer value and initialises my_val with it, and two member functions: get_val that returns the value of my_val and set_val that modifies my_val.
- The class My_Class const object is formed and given the initial value of 10 in the main function. My_Obj is const, so calling the set_val member function on it would try to change the object's state and is therefore not allowed.
- The get_val member function prints my_val's value to the console. The value provided by get_val has the ability to remain the same for every instance of My_Obj's existence because My_Obj is const.
Conclusion:
The const keyword in C++ can be used to denote that values or states of function arguments, class data members, variables, class objects, and pointers cannot be changed. By eliminating unauthorised modification of crucial data, this increases the safety and reliability of C++ programming.