Access anonymous C ++ Subobject (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 can I call the Parent operator inside the Child operator? It just gives me the error "invalid use of parent :: parent"

+3


source to share


1 answer


c.Parent

is not valid syntax and your function is operator<<

not yours. To invoke the proper overload, change the context c

:



ostream& operator<<(ostream& os, const Child& c)
{
    os << static_cast<const Parent&>(c);
    return os;
}

      

+4


source







All Articles