Marking a function as const: what does the compiler do?

Hi everyone, I'm trying to understand what happens when a function is marked as const in a class. Consider the following simple class, where a function foo is used as a test function.

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
#include <iostream>

class ptrclass
{
private:
    int *elem;

public:
    ptrclass(int i) : elem{new int[i]} {}

    void foo() const
    {
        elem[2] = 9;
    }

    ~ptrclass()
    {
        delete[] elem;
    }
};

int main()
{
    ptrclass p{10};
    p.foo();


    return 0;
}


Since foo() is marked as const, then I know that the compiler puts a const in front of int *elem;, BUT as you can see, the code compiles even if I modify what is pointed to by elem

Question: I'd conclude that the compiler does write

int *const a; (constant pointer to an integer)

instead of

const int* a; (pointer to a constant integer)

because I get no compiler error. Is this correct?
Last edited on
Right, the 'const' here does NOT propagate through to the data that is being pointed to. The pointer itself is const, and it will only be a compiler error to change the pointer itself in a const member function.

There's a proposal for a class that does magic to allow const to propagate.
https://en.cppreference.com/w/cpp/experimental/propagate_const
I have not personally tried it out, though.
Last edited on
Thanks Ganado for your quick reply and check.

Actually, I was expecting const int* a; to be used.

Just one last quick question: is it correct to say that const int* a means that "a is a pointer to a constant integer"?

I know that the above syntax, in practice, implies that I can't change the data pointed to by a, i.e. I can't do something like a[2] = 3;. But this is a bit weird to me, because actually I have an array of constant integers!

Please tell me what is the correct way in your opinion
Last edited on
const int* a means that "a is a pointer to a constant integer"?
Correct. Sometimes, it's more helpful to read the syntax right-to-left: "pointer to int that is const".

Then, int *const could be read as, "a const pointer to an int".

and const int * const would be "const pointer to a const int"
(same thing as int const * const)
Last edited on
Topic archived. No new replies allowed.