static data in a sub-class
Ali Çehreli
acehreli at yahoo.com
Sun Dec 23 14:29:06 PST 2012
On 12/23/2012 02:08 PM, Steve D wrote:
> Let's say it's a game and the objects are creatures.
Thanks for giving more context. It helps to see meaningful names to
understand code better.
> class Creature {
> abstract void move();
> }
That's very reasonable.
> class Monster :Creature {
> static float[3] hi = 1;
>
> this(float[] x=null) {if (x) hi = x;}
That is a bad idea. x is passed to a single Monster object but the 'hi'
static member of the whole Monster class gets affected. Just because
there is a SwiftMonster, all Monsters become swift.
This shows that it would be better to mark 'hi' as immutable to avoid
such mistakes.
> Why Ali? Why?
> Why aren't things simple?
:) I still think making Monster a template is a better way to go:
import std.stdio;
class Creature {
abstract void move();
}
class MonsterImpl(SubT) : Creature {
final void run() { writefln("hi running at %s", SubT.hi); }
override void move() { run(); }
}
class RegularMonster : MonsterImpl!RegularMonster {
static immutable float[3] hi = 1;
}
class SwiftMonster : MonsterImpl!SwiftMonster {
static immutable float[3] hi = 2;
}
void main()
{
Creature[2] creatures;
creatures[0] = new RegularMonster();
creatures[1] = new SwiftMonster();
foreach(c; creatures) c.move();
}
The output:
hi running at [1, 1, 1]
hi running at [2, 2, 2]
Ali
More information about the Digitalmars-d-learn
mailing list