Why does this cast to Base class in virtual function give a segmentation fault?

Posted by dehmann on Stack Overflow See other posts from Stack Overflow or by dehmann
Published on 2010-04-17T03:16:10Z Indexed on 2010/04/17 3:23 UTC
Read the original article Hit count: 379

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?)

© Stack Overflow or respective owner

Related posts about c++

Related posts about cast