[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: Derived classes Up: More C++ Previous: Object-orientated programming

Classes

Classes are at the heart of C++'s object-orientation. In the 1B C++ course, classes were created with data in them, also constructors (routines that are run when an object is created) and member functions were created.

fileptr.cc is an example of a simple class built from scratch. Just as local variables of type int are destroyed when no longer required, so are local objects of user-created classes. The destructor (the routine that's run when an object is destroyed) can be defined to do extra work.

This class has 2 constructors (one for the situation when it's given 2 strings, and the other when it's given a pointer to an open file). It also has a destructor that's called when the object goes out of scope (when the routine it's created in ends, for example). Here, the destructor closes the file automatically.

[fontsize=\small,frame=single,formatcom=\color{progcolor}]
   class File_ptr {
   FILE *p;
   public:
   // 2 constructors
   File_ptr (const char* n, const char* a) { p=fopen(n,a); }
   File_ptr (FILE *pp) {p=pp;}

   // destructor
   ~File_ptr() {fclose(p);}
   // redefinition of (), providing a way to access the file pointer
   operator FILE* () {return p;}
   };


   void use_file(const char* fn)
   {
   File_ptr f(fn,"r");
   // file will be closed when f goes out of scope
   // ...
   }



 

Tim Love
2001-07-05