0

Considering the code

(1) Fruit f1{"Orange"};
(2) Fruit f2{"Lemmon"};
(3) const Fruit ff = f1;
(4) ff = f2;

C++ compiler complains at line (4) that Fruit cannot be assigned to const Fruit. But if I write

(1) Fruit f1{"Orange"};
(2) Fruit f2{"Lemmon"};
(3) const Fruit* ff = &f1;
(4) ff = &f2;

why doesn't the compiler complain at line (4) that Fruit* cannot be assigned to const Fruit* ?

  • 5
    Does this answer your question? [What is the difference between const int\*, const int \* const, and int const \*?](https://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const) – The Dreams Wind Jun 30 '22 at 23:45
  • 1
    Also note that your second example assigns a `const Fruit*` to a `const Fruit*`, since `Fruit*` can implicitly convert to `const Fruit*` – Artyer Jun 30 '22 at 23:53
  • 1
    `const` applies to the thing on its left, unless there is nothing there, then it applies to the thing on its right instead. So, `const Fruit ff` (aka `Fruit const ff`) means that `ff` is a `const Fruit` object, so it can't be modified. Whereas `const Fruit* ff` (aka `Fruit const * ff`) means that `ff` is a non-const pointer to a `const Fruit` object. The `ff` pointer itself can be modified, but the object it is pointing at cannot be modified through that pointer. Also, a pointer-to-const can point at a non-`const` object, but conversely a pointer-to-non-const cannot point at a `const` object. – Remy Lebeau Jul 01 '22 at 00:01
  • 1
    Perfect! I think I understood. Compiler will complain If I write ```Fruit * const ff = &f1; ff = &f2;``` because now ```ff``` is a const pointer to a Fruit. – Roberto Dias Algarte Jul 01 '22 at 00:15
  • 1
    `const` qualifies the thing to its immediate left. (The exception to the rule is when `const` appears first, and then it applies to the thing to its immediate right.) – Eljay Jul 01 '22 at 00:19

0 Answers0