0

I get that const variables inside classes must be static, because the Compiler cant access them at Compile time. But why can I then have a non static Method inside this class which contains a non static const, shouldn´t be then also nonaccessible at Compile time?

class ImmutablePoint {

  void someNonStaticMethod(){
    const v = 3;
  }
}
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
Max Tromp
  • 690
  • 7
  • 13

1 Answers1

0

I get that const variables inside classes must be static, because the Compiler cant access them at Compile time-

The compiler can access whatever it wants. It has access to all of your source code, after all.

const members are required to be static to emphasize that const objects are shared and aren't duplicated across instances. (It also wasn't always the case that const class members required static.)

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • But what would be so bad to have duplicates? – Max Tromp May 03 '19 at 15:34
  • One of the main reasons to use `const` is to have a single, canonical, shared instance used throughout your program. – jamesdlin May 03 '19 at 15:43
  • Alright thanks for the help, but wouldnt it make also sense then to make all methods in such a class static – Max Tromp May 03 '19 at 16:37
  • No, it would not make sense. `const` objects are shared instances, but each instance can still have its own data. Suppose you have `const ImmutablePoint(1, 1)` and `const ImmutablePoint(2, 3)` objects. It does not make sense for `ImmutablePoint` to have `static` `x` and `y` members. It also would not make sense to have, say, a `static` `distanceFromOrigin()` method. – jamesdlin May 03 '19 at 17:10