[prog] C++ Inheritance

Elizabeth Barham lizzy at soggytrousers.net
Sat May 24 02:43:17 EST 2003


This is probably due to the way you invoked the compiler and linker:

g++ -o ftest fstest.C
/tmp/cclfc7rJ.o: In function `main':
/tmp/cclfc7rJ.o(.text+0x1a): undefined reference to 
`fstream_ext::fstream_ext(int, char const *, int)'
collect2: ld returned 1 exit status
make: *** [fstest] Error 1

Unless all of your code was situated in ftest.C, then there is no
fstream_ext code for your main function to link up against.

This may work:

  g++ -o ftest ftest.C fstream_ext.C

another method:

  g++ -c fstream_ext.C
  g++ -o ftest ftest.C fstream_ext.o

but there are some other errors in your code.

        strcpy(filename, _fname);

This is actually backwards

       char *strcpy(char *dest, const char *src);

and you'll note the use of const char * in the second argument (the
source) and the const not defined for the definition, which makes
sense since the destination *isn't* constant; whatever is there will
be overrun with the contents of src. Plus you'll need to allocate
memory off the freestore to put the string in:

class ... {
private:
  char * _fname; // we'll assign to it so it shouldn't be const
}

in the constructor:

_fname = new char[strlen(filename + 1)]; // + 1 for the null character
strcpy(_fname, filename);

and in the destructor:

delete [] _fname;

But as for the odd compiler message, I guess it is an inheritence
issue carried over from fstream:

class fstream : public fstreambase, public iostream {
  public:
    fstream() : fstreambase() { }
    fstream(int fd) : fstreambase(fd) { }
    fstream(const char *name, int mode, int prot=0664)
	: fstreambase(name, mode, prot) { }
    fstream(int fd, char *p, int l) : fstreambase(fd, p, l) { } /*Deprecated*/
    void open(const char *name, int mode, int prot=0664)
	{ fstreambase::open(name, mode, prot); }
};

Linking of C++ code is somewhat of a cryptic art and perhaps in the
chain of inheritance a call to fstream(int, char *, int) was called?

Elizabeth


More information about the Programming mailing list