Instructors' Guide

Introduction Terminology Expressions Control Objects Inheritance Technology Summary


Despite the (at first sight) overwhelming possibilities of defining values and control, the essence of programming in C++ must be the development of the abstract data types. To illustrate the difference between C and C++, let us first look at the realization of abstract data type in a procedural way in a C style (employing references), and then at the realization in C++ employing the class construct. Note that in plain C, pointers must be used instead of references.

ADT in C style

  struct ctr { int n; }
  void ctr_init(ctr& c) { c.n = 0; }
  void ctr_add(ctr& c, int i) { c.n = c.n + i; }
  int ctr_val(ctr& c) { return c.n; }


  ctr c; ctr_init(c); ctr_add(c,1); 
  ctr* p = new ctr; ctr_init(*p); ctr_add(*p);  

slide: C++ -- objects (1)

The ctr type defined in slide cc-objects-1 may be regarded as a standard realization of abstract data types in a procedural language. It defines a data structure ctr, an initialization function {\em ctr_init}, a function {\em ctr_add} to modify the value or state of an element of the (abstract) type and an observation function {\em ctr_val} that informs us about its value. We may either declare a ctr object or a pointer to a ctr instance and invoke the functions as indicated.

ADT in C++

  class ctr {
     ctr() { n = 0; }  
~ctr() { cout << "bye"; };
void add( int i = 1) { n = n + i; } int val( ) { return n; } private: int n; };


  ctr c; c.add(1); cout << c.val(); 
  ctr* p = new ctr(); c->add(1); ...

slide: C++ -- objects (2)

In contrast, to define (the realization of) an abstract data type in C++, we employ the class construct and define member functions (or methods) that operate on the data encapsulated by instances of the class. See slide cc-objects-2.