Why can't structs be derived from?

Ali Çehreli acehreli at yahoo.com
Tue Mar 15 13:21:14 PDT 2011


On 03/15/2011 12:54 PM, Daniel Gibson wrote:

 > Furthermore I find C++'s class handling quite unfortunate.. only having
 > polymorphism when explicitly using pointers really sucks.
 > e.g. you have a base class Foo and a class Bar derived from Foo.. now 
you wanna
 > put Objects of type Foo and Bar in a list.. what do you do?
 > list<Foo>? won't work for Bar Objects. So you gotta use list<Foo*>.
 > Using list<Foo*>  really sucks, especially with iterators.. you end 
up using
 > something like
 >    list<Foo*>::iterator it = ... ;
 >    (*it)->x = 3;
 >    int bla = (*it)->myFun(42);
 >
 > Now *that* is ugly.

I am changing the topic here a little but C++ has more problems as 
witnessed in the above code. Normally the objects in the list are 
created by 'new', and not exception-safe for that reason to be left 
naked in a list.

A safe idiom is to use a copyable smart pointer, e.g.

     list<shared_ptr<Foo> >::iterator it = ...;

D's classes' being reference types and its garbage collector help a lot 
in that regard:

     list!Foo myList;  // can hold Bars too

But that's a different topic... :)

Ali



More information about the Digitalmars-d mailing list