Call operator<< for a base class from within operator<< for a derived class, when they are not class members in C++

I have a base b and a derived d classes. Within operator<< for d (which is not a class member) I want to call operator<< for b, plus other actions. I used static_cast for that.

Is there any other way to achieve the same? What are pros and cons of the alternatives?

class b {
};

class d : public b {
};

ostream& operator<<(ostream& os, const b& bi) {
    os << "base";
    return os;
}

ostream& operator<<(ostream& os, const d& di) {
    // call operator for the base class...;
    os << static_cast<b>(di) << endl;
    os << " ... and derived";
    return os;
}

Upvotes: 0

Views: 652

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596703

This would be better handled by defining only 1 operator<< for just b, and then add a virtual method in b for that operator<< to call, and then have d override that method, eg:

class b {
public:
    virtual void printTo(ostream& os) const;
};

class d : public b {
public:
    void printTo(ostream& os) const override;
};

ostream& operator<<(ostream& os, const b& bi) {
    bi.printTo(os);
    return os;
}

void b::printTo(ostream& os) const {
    os << "base";
}

void d::printTo(ostream& os) const {
    b::printTo(os);
    os << endl << " ... and derived";
}

Upvotes: 4

Related Questions