Question

If you look at <streambuf>header file in VS2010 you'll see the definition of this member function as

pos_type pubseekoff(off_type _Off, ios_base::seekdir _Way,
                ios_base::openmode _Mode = ios_base::in | ios_base::out)
{   // change position by _Off, according to _Way, _Mode
    return (seekoff(_Off, _Way, _Mode));
}

where seekoffis a virtual function, which is overridden in the derived classes basic_filebuf and basic_stringbuf and which does nothing in the base class basic_streambuf as can be seen below:

virtual pos_type seekoff(off_type, ios_base::seekdir,
                         ios_base::openmode = ios_base::in | ios_base::out)
{   // change position by offset, according to way and mode
    return (streampos(_BADOFF));
}

I couldn't find the definition of _BADOFFbut it's probably -1. But that really doesn't matter here. This function, nor pubseekoff, will never be invoked, as the class basic_streambufis an abstract class (its constructors are protected).

Note also that the gcc compiler uses the same technique. Why did the two compilers have to resort to the seekoff() member functions, instead of simply declaring pubseekoff as pure virtual in basic_streambuf and defining it in each one of the derived classes basic_filebuf and basic_stringbuf?

Was it helpful?

Solution

For the same reason you don't normally make virtual functions public. Public functions define an interface, and the base class needs to be able to capture them if it wants to enforce that interface. There are exceptions, when inversion of control is involved, but in most cases, you simply don't make virtual functions public. How would you insert pre- and post-condition checks if you did? (See http://www.gotw.ca/publications/mill18.htm, for example.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top