Amit
Amit

Reputation: 6304

Using an overloaded method of the parent

I have two classes: Father, and Son. Son extends Father.

Both, are overloading the ostream operator.

class Father {
public:
    friend ostream& operator<<(ostream& os, Father& v); //prints "father"
};

class Son : public Father {
public:
    friend ostream& operator<<(ostream& os, Son& v); // prints "son"
};

Is there a way, that from Son I can call Father's "<<" ?

I want that Son will eventually print: "father son"

Upvotes: 0

Views: 102

Answers (2)

Mohamad Elghawi
Mohamad Elghawi

Reputation: 2124

You can use virtual method overriding.

class Father
{
public:
    virtual std::ostream& operator<<(std::ostream& os)
    {
        os << "father";
        return os;
    }
};

class Son : public Father
{
public:
    std::ostream& operator<<(std::ostream& os) override
    {
        Father::operator<<(os);
        os << " son";
        return os;
    }
};

But as TartanLlama mentioned this would switch the arguments of the operator so you would end up using it like so:

Son s;
s << std::cout;

Upvotes: 1

TartanLlama
TartanLlama

Reputation: 65620

You can static_cast the Son& to a Father&:

class Son : public Father {
public:
    friend std::ostream& operator<<(std::ostream& os, Son& v) {
        os << static_cast<Father&>(v);
        os << "son";   
        return os;
    }
};

Upvotes: 2

Related Questions