I wish to print a derived class while using operator<<. After I print the derived class, I wish to first print its base after which its very own content.

However I went 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 simple ways?

    ((const Base*)this)->Print(out); // infinite, calls this fct recursively
    ((Base*)this)->Print(out);       // segfault (from infinite loop?)

Try Base::Print(out)

Towards the question of why:

  1. ((Base)*this).Print(out); slices current instance to Base-typed temporary. That produces a direct call to base class method.
  2. ((const Base*)this)->Print(out); calls virtual method via a pointer to base, which resolves towards the child class method, which leads to infinite recursion.
  3. ((Base*)this)->Print(out); - I am confident this really is undefined behavior.

use Base::Print rather. Virtual functions are overriden by derived class. Essentially you're calling print again and again