0
class Foo
{
public:
    const int a;
    const int* x;
    int* const y;
    Foo() : a{ 0 }, y{ new int(20) } {
        x = new int(10);
    }
};

int main()
{
    Foo f;
    // f.a = 100; // cannot
    f.x = new int(100);
    // f.y = new int(100); // cannot

}

When const int a is defined as fields of a class, it is called a constant member. It must be initialized in the initializer list and cannot be changed afterwards.

How about const int* x (which is the same as int const* x) and int* const y? Which one should be called as a constant member? If "constant member" is defined as field that must be initialized in the initializer list and cannot be changed afterwards, then the constant member is y rather than x. Am I wrong here?

Edit

According to IntelliSense, y is a constant member.

enter image description here

OK. I am sure I am not wrong. I will delete this question shortly. Thank you for your participation!

1 Answers1

3

The "const int* x" is a (non-const) pointer to a const int. Since x is non-const, it need not be initialized upon construction.

Here are some examples:

class C
{
public:
    C() :
      const_int(1),
      const_int_again(2),
      const_ptr_to_non_const_int(nullptr),
      const_ptr_to_const_int(nullptr)
    {}

private:
    const int const_int;
    int const const_int_again;
    
    const int* ptr_to_const_int; // Doesn't need initialized
    int const* ptr_to_const_int_again; // Doesn't need initialized

    int* const const_ptr_to_non_const_int;
    const int* const const_ptr_to_const_int;
    int const* const const_ptr_to_const_int_again;
};

You may find the cdecl.org website helpful.

Mooing Duck
  • 59,144
  • 17
  • 92
  • 149
PFee
  • 187
  • 9
  • Since it's a c++ question - would be good to add references too - or link to one of the other good answers (e.g. see this question https://stackoverflow.com/questions/2627166/difference-between-const-reference-and-normal-parameter) – Mr R Apr 12 '21 at 22:06
  • And a `T * const * const` vs a `T const * *` – Mr R Apr 12 '21 at 22:07