void pointer syntax

H. S. Teoh hsteoh at quickfur.ath.cx
Mon May 14 12:05:53 PDT 2012


On Mon, May 14, 2012 at 08:40:30PM +0200, Stephen Jones wrote:
> I want an array of different classes of objects. I tried to
> subsume the differences by extending the classes under a single
> interface/abstract class/super class (3 different approaches) all
> to no avail as I could not access the public variables of the
> instantiated classes while storing them in an array defined by
> the interface/super class.
[...]

Every class derives from Object, so an Object[] should do what you want.

Also, if you need to access public variables of a derived class, you
need to downcast:

	// Suppose this is your class heirarchy
	class Base { int x; }
	class Derived1 : Base { int y; }
	class Derived2 : Base { int z; }

	// Here's how you can put derived objects in a single array
	auto d1 = new Derived1();
	auto d2 = new Derived2();
	Base[] o = [d1, d2];

	// You can directly access base class members:
	o[0].x = 123;
	o[1].x = 234;

	// Here's how to downcast to a derived type
	Derived1 dp = cast(Derived1) o[0];
	if (dp !is null) {
		dp.y = 345;
	}

	Derived2 dp2 = cast(Derived2) o[1];
	if (dp2 !is null) {
		dp.z = 456;
	}

Note that the if statements are necessary, since when downcasting you
don't know if the given Base object is actually an instance of that
particular derived object. If you tried cast(Derived1) o[1], it will
return null because o[1] is not an instance of Derived1.


T

-- 
Nothing in the world is more distasteful to a man than to take the path that leads to himself. -- Herman Hesse


More information about the Digitalmars-d-learn mailing list