const makes overload faster?

Hello,

I'm working on a class that overloads operators and I was told that by adding const in the parameters and at the end of the declaration I could make them faster.

Could someone explain why that is/how that works?

Thank you in advance,
Friso
There are potential situations in which using const allow compiler to do some optimizations by calculating in compile-time, rather than run-time, but this is not the main reason for using const in operators. You place const in overloaded operator functions to make sure that any arguments passed to it will not be changed directly (as anyone would expect), as in below example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>

class Pair
{
public:
	int a;
	int b;

	Pair (int A, int B);
	Pair operator+ (Pair & other); 

};

Pair::Pair (int A, int B) {this->a = A;	this->b = B;};

Pair Pair::operator+ (Pair & other)
{
	Pair result(this->a + other.a, 
				this->b + other.b);

	// The below is legal, but 
	// hardly expected for what
	// should operator+ do
	other.a += 99999999; // Constness prevents such
	this->a += 99999999; // alterations to arguments.
	/////

	return result;
}

int main()
{
	Pair one(1,1);
	Pair two(2,2);
	Pair three(0,0);
	
	std::cout << "one:\t" << one.a << ", " << one.b << "\n" 
			  << "two:\t" << two.a << ", " << two.b << "\n" 
			  << "three:\t"<< three.a << ", " << three.b << "\n\n";

	
	three = one + two; // now both one and two are changed!
	std::cout << "after one+two: \n\n";
	std::cout << "one:\t" << one.a << ", " << one.b << "\n" 
			  << "two:\t" << two.a << ", " << two.b << "\n" 
			  << "three:\t"<< three.a << ", " << three.b << "\n\n";
}
There's also the convenience factor, a function or operator that takes a const variable can also take a regular variable, but a function or operator that is made to take a regular variable can't legally take a const variable because the compiler decides that there is a possibility of the const variable being altered.

It's good practice to make a function or operator accept a const variable whenever possible.
@JockX
So if I'm to understand correctly writing the overload like this:
Pair operator+ (const Pair & other);
Will prevent:
other.a += 99999999;

So does that mean that adding another const at the end like so:
Pair operator+ (const Pair & other) const;
would prevent:
this->a += 99999999;?

@newbieg
Thank you, I'll be sure to put that into practice.

@Friso1990 - that's right.
Topic archived. No new replies allowed.