Bug with offsetof?

jerro a at a.com
Sun Nov 25 20:03:06 PST 2012


This works for me if I add parentheses to the line where you get 
the error like this:

writeln(TestStruct().x.offsetof);//bug here

The error you were getting is not related to offsetof. The 
problem seems to be that if you write TestStruct.x inside a 
non-static method, the compiler thinks you are trying to get 
member TestStruct.x of the current instance. You obviously can't 
do that because the current instance is not a TestStruct. I've 
never used this feature, but it seems you can access members like 
this:

class Foo
{
     int x = 42;

     void test()
     {
         writeln(Foo.x); // prints 42
     }
}

Doing this seems pretty pointless, though. I assume the reason 
behind this is to allow you to access the members of a superclass 
that are named the same as current classes members, like this:

class Parent
{
     int x = 1;
}

class Child : Parent
{
     int x = 2;

     void test()
     {
         writeln(x);
         writeln(Parent.x);
     }
}

(new Child).test() prints:
2
1

When you add parentheses after TestStruct, you create an instance 
of TestStruct, and then you access its member x, so there is no 
ambiguity.



More information about the Digitalmars-d-learn mailing list