Using the const keyword to optimize your code
We have already seen in previous recipes that a const keyword is used to make data or a pointer constant so that we cannot change the value or address, respectively. There is one more advantage of using the const keyword. This is particularly useful in the object-oriented paradigm.
Getting ready
For this recipe, you will need a Windows machine and an installed version of Visual Studio.
How to do it…
In this recipe, we will find out how easy it is to use the const keyword effectively:
#include <iostream>
class A
{
public:
void Calc()const
{
Add(a, b);
//a = 9; // Not Allowed
}
A()
{
a = 10;
b = 10;
}
private:
int a, b;
void Add(int a, int b)const
{
std::cout << a + b << std::endl;
}
};
int main()
{
A _a;
_a.Calc();
int a;
std::cin >> a;
return 0;
}How it works…
In this example, we are writing a simple application to add two numbers. The first...