c++operator-overloading

How to overload operator in base-derived classes?


As shown in https://godbolt.org/z/WhEqjaehc

Code is like

#include <filesystem>
#include <fstream>
#include <iostream>

class BaseFile {
protected:
    std::ofstream file;

public:
    template<typename T>
    BaseFile &operator<<(const T &v) {
        file << v;
        return *this;
    }
    BaseFile &operator<<(std::ostream &(*pf)(std::ostream &) ) {
        file << pf;
        return *this;
    }
};

class TmpFile : public BaseFile {
public:
    template<typename T>
    TmpFile &operator<<(const T &v) {
        //some additional operation into file
        file << v << "some suffix maybe";
        return *this;
    }
    TmpFile &operator<<(std::ostream &(*pf)(std::ostream &) ) {
        file << pf;
        return *this;
    }
};

int main(){
    TmpFile f("path");
    f << "123" << std::endl;
}

BaseFile is a base class and TmpFile is derived from it. If I want to change std::ofstream file in BaseFile into private, then how to implement operator<< in TmpFile without directly using file?


Solution

  • You can just call base class method explicitly:

        template<typename T>
        TmpFile &operator<<(const T &v) {
            //some additional operation into file
            // file << v << "some suffix maybe";
            BaseFile::operator<<(v);
            BaseFile::operator<<("some suffix maybe");
            return *this;
        }
        TmpFile &operator<<(std::ostream &(*pf)(std::ostream &) ) {
            BaseFile::operator<<(pf);
            return *this;
        }
    

    Godbolt demo.

    It is also possible to chain the calls:

    BaseFile::operator<<(v).BaseFile::operator<<("some suffix maybe");
    BaseFile::operator<<(v) << "some suffix maybe";
    

    but for me it's less readable.