2

I'm a beginner to C++ and I have a question that I want to make sure...I've done pretty of searching online.

Let say I have a class call A and it has a function called Afunction. The function looks like:

// this is pseudocode
void Afunction (const A& a)
{
 a.something = a.something +1;
}

My understanding is we have an "pointer-like" thing called 'a' and it's an alias to whatever we pass in. Here we only make sure the alias itself is const, but no guarantee that the value to which it points at won't be changed. In fact, I'm changing it..and I don't get no error.

So my question is, how can I make sure the values that the alias is point to can't be changed? It's much easier to be done if it's pointer other than alias...

Thanks in advance.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
user1447343
  • 1,417
  • 4
  • 18
  • 24

3 Answers3

2

If a compiler accepts that code, you should ditch it immediately.

You can't modify a.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

A const& (which is unforunately equivalent to const A&) is a reference to a const object.

Similarly, A const* is a pointer to a const object, whilst A * const is a const pointer to an object and A const * const is a *const pointer to a const object`.

The key is to read (and write) your type declarations from right-to-left.

Alex Chamberlain
  • 4,147
  • 2
  • 22
  • 49
2

It all depends on what is something.

If you posted the code of class A, it would be easier to explain why you can change something.

In general, you can't modify contents of const A&. But...

  • something can be static, then const doesn't matter since something doesn't technically belong to the a variable in Afunction.
  • something can be declared mutable. Sometimes having a member variable that can be changed even when the object is const is beneficial. For example, reference counting.
  • something may be something completely different, with weird semantics. (as Zyx 2000 pointed out).
milleniumbug
  • 15,379
  • 3
  • 47
  • 71