Accessing private class members with tupleof
grauzone
none at example.net
Thu Jan 29 00:51:53 PST 2009
Is it legal to access private members of a class using tupleof, when
normal access would be illegal?
It is not really clear from the D1.0 specification:
> The .tupleof property returns an ExpressionTuple of all the fields in
> the class, excluding the hidden fields and the fields in the base
> class.
Do private members count as hidden, or does the specification only
consider the vtable and monitor fields as hidden fields? What exactly
are "hidden fields" at all?
It seems newer dmd versions allow you to access private members, while
older versions raise a compile-time error.
Here is an example to demonstrate the issue (for D1.0):
---file a.d
module a;
class Test {
int a = 1;
protected int b = 2;
private int c = 3;
package int d = 4;
}
---file b.d
module b;
import a;
int[] get(Test t) {
int[] result;
foreach (i, x; t.tupleof) {
result ~= t.tupleof[i];
}
return result;
}
import std.stdio;
void main() {
//outputs [1,2,3,4]
writefln(get(new Test()));
}
More information about the Digitalmars-d-learn
mailing list