Re: Deriving from concrete types like std::list
On Jul 7, 6:42 am, Alexander Bartolich <alexander.bartol...@gmx.at>
wrote:
Urs Thuermann wrote:
[...]
class StmtList : public Stmt, public std::list <Stmt *>=
{
public:
virtual void exec() {
const_iterator it;
for (it = begin(); it=
!= end(); ++it)
exec();
}
};
// in the parser
stmt_list->push_back(stmt);
Is this, according to Stroustrup, the wrong approach? Instead of
deriving I could have a member of type list <Stmt *> in class StmtList
but iterating would look more cumbersome and I had to implement my own
push_back() that calls push_back() for that list member, etc. After
all, a statement list *is* a list. Shouldn't I express this
relationship by derivation?
Oh, my. There are two arguments against this.
First, the nice one: by deriving from std::list you make the interface
of StmtList extremly large. This gives users of StmtList a lot of ways
to mess with its content. Which means that you cannot deduce the behav-
iour of the class from its methods alone. You always have to check that
nobody out there does nothing stupid with its instances. This totally
defeats the reason we are doing OOP.
While many of the STL classes are not intended for *PUBLIC*
derivation,
private derivation seems OK. Note, for example,
std::priority_queue<>,
which has protected members. However, it's destructor is not virtual,
so you probably shouldn't publicly derive.