Using in one class a constant defined in another class
Paul Backus
snarwin at gmail.com
Tue Nov 16 18:34:12 UTC 2021
On Tuesday, 16 November 2021 at 18:12:34 UTC, chopchop wrote:
> Hi,
>
> I have a class Ground which defines some playground constants
> (at least constant to the class):
> ```
> class Ground
> {
> immutable WALL = -2;
> immutable playgroundWidth = 77;
> immutable playgroundHeight = 22;
>
> ...
> }
> ```
> Now, in another class "Player", I would like to use those
> playground constants:
> ```
> import ground;
> class Player
> {
> this()
> {
> x = Ground::playgroundWidth/2;
> y = Ground::playgroundHeight/2;
> }
> ...
> }
> ```
> I used the "::" notation as a reference to C++, but obviously
> here it does not compile:
> |Error: need `this` for `playgroundWidth` of type
> `immutable(int)`|
The reason you get this error is that you have declared
`playgroundWidth` and `playgroundHeight` as instance variables of
`Ground`. Of course, in order to access an instance variable, you
need to have an instance. When the compiler says "need `this`",
it means you need an instance of the class.
The correct fix is to declare the variables as `static`:
```d
class Ground
{
static immutable WALL = -2;
static immutable playgroundWidth = 77;
static immutable playgroundHeight = 22;
}
```
As far as I know, this works the same way in D as it does in C++.
Here's an example of C++ code that has the same error:
```c++
class C
{
public:
int x = 42;
};
int main()
{
// error: invalid use of non-static data member 'C::x'
int y = C::x;
return 0;
}
```
Interactive version: https://godbolt.org/z/a5xvzooev
> My question is : Is enum declaration the right way to go? Or
> did I just find a trick around the problem? Could not find
> anything in the documentation. Why enum works and immutable
> does not?
The version with the enum declarations works because enum
declarations are always considered `static`.
More information about the Digitalmars-d-learn
mailing list