What Is The Importance Of Using "const" in C++?

Hello Professionals,

Would like to ask why const is important in C++?? (for example)

1
2
3
4
5
6
7
8
class Entity
{
public:
	void Print() const {
		cout << "Hello!" << endl;
	}

};


On the other hand, removing the const has no effect at all (which means same output).

1
2
3
4
5
6
7
8
class Entity
{
public:
	void Print() {
		cout << "Hello!" << endl;
	}

};
Last edited on
the output looks the same to you, but how the compiler builds the code can change if you look at the assembler listing for more complicated examples. At times const can help the compiler make better code (performance). This is on top of correctness, but as is often the case, you can't see the differences (if there are any) without really digging deep.



Some guns have a safety switch. It makes no difference when you intentionally fire the gun, but could prevent accidental misuse. The const is no different.


Btw, "removing the const" does have an effect. You simply did not test it enough to notice.
1
2
3
4
5
6
7
8
9
int main() {
  Entity foo;
  foo.Print();

  const Entity bar;
  bar.Print();

  return 0;
}
Last edited on
I tried to run both syntax and they have the same output. :(

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Entity
{
public:
	void Print() const {
		cout << "Hello!" << endl;
	}

};
int main() {
Entity foo;
foo.Print();

const Entity bar;
bar.Print();

return 0;
}


Output:

Hello!
Hello!
Contrary to what jonnin said, marking a function as const does not give the compiler any information that is useful when optimizing the code so it should make no difference on the generated assembly what so ever.

I tried to run both syntax and they have the same output.

Yes, that's how it's supposed to be. Now remove const from the function and the second call will fail to compile for no good reason. I mean, why wouldn't you be able to print a const object? Printing the object does not modify the object so of course you should be able to print a const object but for this to work the function must be marked as const.
Last edited on
Your first test had:
1. non-const object, non-const member
2. non-const object,     const member

Your second test had
3.     const object,     const member
2. non-const object,     const member

Like Peter87 said, you haven't yet tested:
4.     const object, non-const member

Thanks @keskiverto and @Peter87 for the insights. I understand it now. God bless. :)
Topic archived. No new replies allowed.