Problem using Interfce
H. S. Teoh
hsteoh at quickfur.ath.cx
Mon May 14 12:30:09 PDT 2012
On Mon, May 14, 2012 at 12:15:32PM -0700, Ali Çehreli wrote:
> On 05/14/2012 11:40 AM, Stephen Jones wrote:
> > I want an array of different classes of objects.
>
> So far, Object[] makes sense.
>
> > 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
>
> Yeah, that is a fundamental example of object oriented design. Thank
> you for showing us some code below. It help a lot.
>
> > as I could not access the public variables of the instantiated
> > classes while storing them in an array defined by the
> > interface/super class.
>
> Makes sense because neither the interface nor the super class has
> such members. D's polymorphism does not have virtual values (nor
> does C++'s, the other object oriented language that I know well).
> Polymorphism is about virtual member functions.
D's @property attribute does allow you to simulate virtual data members,
though:
class Base {
private int _width, _height;
this() { _width = 1; _height = 1; }
@property int width() { return _width; }
@property int height() { return _height; }
}
class Derived : Base {
// Look, ma! .width is a virtual value!
override int width() { return 0; }
}
void main() {
auto obj1 = new Base;
assert(obj1.width == 1);
auto obj2 = new Derived;
assert(obj2.width == 0);
}
> What you can do is to force the subclasses provide the data through
> virtual functions.
You can also downcast. But downcasting generally should be avoided
because it breaks the Liskov Substitution Principle. It's better to
provide virtual functions to access derived class data.
> (An alternative is to use compile-time polymorphism through
> templates. They provide data virtualization. (See range interfaces
> like InputRange. For example, the return type of front() is not
> specified by InputRange. Ranges can be of any type of elements.))
[...]
Templates are instantiated at compile-time, though. It won't work if
what you put in the list changes at runtime.
T
--
"How are you doing?" "Doing what?"
More information about the Digitalmars-d-learn
mailing list