I want to print out a derived class using the operator<<
. When I print the derived class, I want to first print its base and then its own content.
But I ran into some trouble (see segfault below):
class Base {
public:
friend std::ostream& operator<<(std::ostream&, const Base&);
virtual void Print(std::ostream& out) const {
out << "BASE!";
}
};
std::ostream& operator<<(std::ostream& out, const Base& b) {
b.Print(out);
return out;
}
class Derived : public Base {
public:
virtual void Print(std::ostream& out) const {
out << "My base: ";
//((const Base*)this)->Print(out); // infinite, calls this fct recursively
//((Base*)this)->Print(out); // segfault (from infinite loop?)
((Base)*this).Print(out); // OK
out << " ... and myself.";
}
};
int main(int argc, char** argv){
Derived d;
std::cout << d;
return 0;
}
Why can't I cast in one of these ways?
((const Base*)this)->Print(out); // infinite, calls this fct recursively
((Base*)this)->Print(out); // segfault (from infinite loop?)