Tuesday, June 26, 2007
Use private inheritance judiciously
compilers dont convert a derived class object into a base class object automatically if you privately inherit
private inheritance means you want to exploit some features available in base class, and not that their is any conceptual relationship between them
use composition whenever you can, use private inheritance when you must..genrally when protected or virtual functions are in picture and in edge cases space concerns ....I dont understand this point ?
having a composition object inside yourself, you can prevent derived classes from redefining your inherited virtual functions.
now edge case: think class with no data ( no non static data , no virtual functions, no virtual bases)such an empty class would have size more than 1 due to c++ technical issues...generally compiler inserts a char, depending on alignment etc you might see different size increase.
c++ decrees that free standing objects must have non zero size.
class holdsint { int x ; empty e } has size more than int
Empty base optimization class holdsint:private empty { int x } has size int....its generally viable under single inheritance only.
rules governing c++ object layout generally mean that the ebo cant be applied to derived classes that have more than one base
generally empty classes have typedefs enums static data non virts etc.....stl has a no of empty classes....e.g. unary_function and binary_function
private inheritance is most likely to be a legitimate design strategy when you are dealing with two classes not related by is a where one either needs a ccess to the protexted members of another or need to redefine one or more of its virtual functions.
things to remember:
private inheritance means is implemented in terms of . its usually inferior to composition but it makes sense when a derived class needs access to protected base class members or needs to redefine inherited virtual functions
uinlike composition privaet inheritance can enable the empty base optimization . this can be important for library developers who strive to minimize object sizes.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment