Sunday, July 1, 2007

use multiple inheritance judiciously

in mi it comes becomes possible to inherit the same name ( function,typedef etc) from more than one base class....potential ambiguity
class borrowableitem{
public:
void checkout();
};
class electronicgadget{
private :
bool checkout() const;
}
class mp3player: public borrowable, public electronicgadget { }
mp3player mp3

mp3.checkout() is ambigous because to find hte appropriate function to call c++ doesnt worry about its access level.

deadly diamond
whenever you have diamond think whether their should be only one copy of the base class or it should be one per path.
if you only want one copy of the base class then make the derived classes have a virtual inheritance. e.g.
class file {}
class inputfile : virtual public file {...}
class outputfile: virtual public file {...}
class iofile: public inputfile, public outputfile {,,}
what structure of outputfile was just normal inheritance ?
what if outputfile has virtual private inheritance ?

STL has a similar class hierarchy in basic_ios, basic_istream , basic_ostream and they are all templates

the reponsiblity for initializing a virtual base class is born my the most derived class....that means a derived class has to be aware of a virtual base, independent of how far down it is

try not to use virtual inheritance. if you must try not to put data members in there.

inheritance is necessary if virtual functions are to be redefined

things to remember:
multiple inheritance is more complex than single inheritance., it can lead to new ambiguity issues and to the need for virtual inheritance.
virtual inheritance imposes costs in size speed and complexity of initialization and assignment. its most practical when virtual base classes have no data.
multiple inheritance does have legitimate uses. one scenario involves combining publid inheritance from an interface class with private inheritance from a class that helps the implementation.

No comments: