Techniques

In addition to the elements introduced thus far, C++ offers a number of other features that may profitably be used in the development of libraries and programs. See slide cc-tech-1.

Techniques


slide: C++ -- techniques (1)

For instance, C++ offers templates (to define generic classes and functions), overloading (to define a single function for multiple types), friends (to bypass protection). type conversion (that may be defined by class constructors or type operators), type coercions (or casts, that may be used to resolve ambiguity or to escape a too rigid typing regime), and smart pointers (obtained by overloading the dereference operator). In section delegation, examples are given of how these features may be used.

To get some of the flavor of using C++, look at the definition of the ctr class in slide cc-tech-2 employing multiple constructors, operators, default arguments and type conversion.


  class ctr { 
\fbox{C++}
public: ctr() { n = 0; } void operator++() { n = n + 1; } int operator()() { return n; } operator char*() { return "aCounter"; } private: int n; };

Usage

  ctr c; c++; cout << (char*) c << " is " << c();
  

slide: C++ - techniques (2)

The ctr provides two constructors, one with an integer argument (which is by default set to zero, if omitted) and one with a string argument (that expects a valid coding of an integer as a string). The increment operator is used to define the function add (which also has a default argument to increment by one), and the application operator is used instead of val. Also, a type conversion operator is defined to deliver the value of the ctr instance anywhere where an integer is expected. In addition, a type conversion operator (employing a conversion function from integers to (char*) strings) is used to return the value of the ctr instance as a string.

Again, the difference is most clearly reflected in how an instance of ctr is used. This example illustrates that C++ offers many of the features that allow us to define objects which may be used in a (more or less) natural way. In the end, this is what software development is about, to please the user, within reason.