Department of Engineering

IT Services

CUED Talk: Extending C++

C not only had built-in types (like int, float etc) but offered a way to invent new types. Doing

  typedef struct vector {
  float x;
  float y;
};

made it possible to then do

  vector v;
  v.x=3;
  v.y=7;

In C++ you can take things further, creating classes that can contain not only data but functions too, so

  class vector {
  float x;
  float y;
  int fun();
};

and then

  vector v;
  v.x=3;
  v.fun();

is possible. Something like this can be simulated in C, but C++ has further facilities for developing new types that C can't simulate. For example, once you've created a new type you'd want to use it in calculations - addition for example. In C, the only way to add vectors would be to write a routine so that you could do

  vector v3=add_vectors(v1,v2);

but in C++ you can extend the meaning of the + sign so that

  vector v3=v1+v2;

becomes possible. The rest of this talk shows how to do this. To do it properly involves quite a lot of work (the standard library is a lot of code!) so later in the talk I'll show ways to reduce the workload. Not everything will be explained but you may well be able to adapt the code without fully understanding it.