![[Dept of Engineering]](http://www.eng.cam.ac.uk/images/house_style/engban-s.gif)
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
// ...
}