[prog] C++ Inheritance

Elizabeth Barham lizzy at soggytrousers.net
Fri May 23 11:59:17 EST 2003


   Try placing "explicit" before the construtor's declaration and
not before the constructor's definition. e.g.:

#include <fstream>

class Fstream_ext : public fstream {
private:
  const char * _fname;
public:
  explicit Fstream_ext(const char *filename, openmode = in|out);
};

Fstream_ext::Fstream_ext(const char *filename, openmode mode)
        :fstream(filename, mode) {
        _fname = filename;
}

   Its important that explict constructors are declared in the class
so that the compiler will not attempt an automatic type conversion
with your class in other source files, source files that may #include
the definition of your class. That is to say, the "explicit" keyword
defines a compiler-enforced constraint for users of your class and had
the "explicit" keyword been used in the constructor's definition
rather than the declaration, other source files would not be aware of
the constraint and could do such things as:

#include "fstream_ext.h"

 ... 

   Fstream_ext f = "pot-o-gold.txt";

As it is, of course, the compiler flags it as an error albeit with a
somewhat cryptic message.

Elizabeth


More information about the Programming mailing list