"this" reference not working?
Jarrett Billingsley
kb3ctd2 at yahoo.com
Sun Apr 8 08:52:24 PDT 2007
"OP" <OP at nothing.com> wrote in message news:evb2c0$2bel$1 at digitalmars.com...
>
> Nope, because you still make use of "this" pointer. I need an option that
> wouldn't need the pointer or in which the pointer correctly points to the
> caller of the contructor.
"this" is working just fine. Believe me, I think people would have had
problems by now if it wasn't.
The thing is that you can't have "virtual members." You can't override a
data member and have it be referenced through a class instance pointer
virtually. I.e. this (which is basically what you're doing) won't work:
class A
{
static int x = 5;
void printX()
{
// this x references A.x, regardless of what type 'this' is
writefln(x);
}
}
class B : A
{
static int x = 10;
override void printX()
{
super.printX();
}
}
void main()
{
A a = new A();
// Prints 5
a.printX();
B b = new B();
// Also prints 5
b.printX();
}
"this.x" in any method (including the constructor) of A will always refer to
A.x, because you're allowed to access static members through class
instances.
This has to be done using a virtual method, i.e.
class A
{
static int x = 5;
void printX()
{
// now this uses a virtual call
writefln(getX());
}
int getX()
{
return x;
}
}
class B : A
{
static int x = 10;
override void printX()
{
super.printX();
}
override int getX()
{
// this is one of B's methods, so it returns B.x
return x;
}
}
void main()
{
A a = new A();
// Prints 5
a.printX();
B b = new B();
// Now prints 10
b.printX();
}
More information about the Digitalmars-d-learn
mailing list