Thursday, March 24, 2011

A question of classes

One frequent element of discussion during my interviews is about the different types of classes you can define in C++. In this sense, C++ Coding Standard provides a valuable summary:

  1. Value classes have a public constructor and a public destructor and a copy constructor with value semantics. Also, they have no virtual function, no virtual destructor and so you cannot inherit from them. The idea is that you use value classes for holding other objects and the typical example are STL containers;
  2. Base classes are used as base of a hierarchy. Therefore you can have a virtual public destructor, or in very rare cases a protected non virtual destructor (if you don't want to use polymorphism as in std::unary_function;
  3. Trait classes are template classes with information about types, where you define a certain numbers of typedefs and you never instantiate explicitly the class with a constructor;
  4. Policy classes represents pluggable behaviour and it is usually instantiated as a base or a member;
  5. Exception classes mix a value and reference semantics since they throw the exception by value and capture it by reference. Quite frequently they have virtual functions.


No comments:

Post a Comment