Thursday, February 22, 2007

Virtual and private inheritance

Wow, cool. So I just browsed through the excellent "Scientific and Engineering C++" by Barton & Nackman (ISBN 0-201-53393-6), and found this little nugget on inheritance:

If you want your class to inherit both from an interface and from an implementation of that interface (such as IClass and ClassImpl), do virtual inheritance from the interface and private inheritance from the implementation, like:

class MyClass :
public virtual IClass,
private ClassImpl {
};


As expressed by the authors of this masterful piece of litterature, this establishes an "is-usable-as" relation to the interface and a secret "is-implemented-in-terms-of" relation to the implementation. C++ will thus allow you to treat pointers to your class as IClass pointers and at the same time automatically route method calls to the ClassImpl. In other words OOP at its best!

Too bad virtual function calls impose such bad overhead that they're generally abandoned to the favor of template classes nowadays...

No comments:

Post a Comment