Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access anonymous Subobject C++ (cout)

class Parent
{
    ...
    friend ostream& operator<<(ostream&, const Parent&);
};

class Child : public Parent
{
    ...
    friend ostream& operator<<(ostream&, const Child&);
};

ostream& operator<< (ostream& os, const Parent& p)
{
    os << ... ;
    return os;
}

ostream& operator<< (ostream& os, const Child& c)
{
    os << c.Parent << ... ;    // can't I access the subobject on this way?
    return os;
}

How do I call the operator of Parent inside of the operator of Child? That just gives me the error "invalid use of Parent::Parent"

like image 927
SimonH Avatar asked Dec 03 '25 14:12

SimonH


1 Answers

c.Parent is not a valid syntax, neither is your operator<< a member function. To call the proper overload, change the context of c:

ostream& operator<<(ostream& os, const Child& c)
{
    os << static_cast<const Parent&>(c);
    return os;
}
like image 84
Piotr Skotnicki Avatar answered Dec 05 '25 03:12

Piotr Skotnicki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!