On Monday, 14 May 2012 at 19:04:46 UTC, H. S. Teoh wrote:
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

Using Object gives exactly the same problem as the Object super class does not have vcount variable. Casting is not a solution because the reason for throwing different sorts of widgets into a single array was so I did not have to track what each type of object was; not tracking what each object in the array is I have no means of knowing what to cast each Widget in the array to.

If some one knows void pointer syntax that would be helpful. As I understand it there is a type called size_t that takes the address of as a a value. Can I make an array of these and simply initialize each with &button1, &cursor, etc? Also, how is size_t freed?

Reply via email to