Instructors' Guide


Introduction Terminology Expressions Control Objects Inheritance Technology Summary

Technology

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 (which may be defined by class constructors or type operators), type coercions (or casts, which may be used to resolve ambiguity or to escape a too rigid typing regime), and smart pointers (obtained by overloading the dereference operator). An integral part of standard C++ is the Standard Template Library, offering a generic collection of containers, of which a brief description is given in section STL.

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 { 
C++
public: ctr(int i = 0, char* x = "ctr") { n = i; strcpy(s,x); } ctr& operator++(int) { n++; return *this; } int operator()() { return n; } operator int() { return n; } operator char*() { return s; } private: int n; char s[64]; };

Usage

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

slide: C++ - techniques (2)

The ctr provides a constructor, with an integer argument (which is by default set to zero, if omitted) and a string argument (that expects a name for the counter). The increment operator is used to define the function add (which by default increments 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 char* type conversion operator is used to return the name of the ctr.

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.