Overloading << and inheritance

Hi everyone!

I have a question about inheritance and overloading <<. I have an abstract base class A, and a publicly derived class B. In both classes I want to overload the operator <<, but in the abstract base class I want to have a default implementation (i.e. some specific output).

By playing around I found one possible solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

class A{
   public:
      friend std::ostream& operator << (std::ostream& s, const A& a){
         s << "A";
         return s;
      }
      virtual void foo() = 0;
};

class B : public A{
   public:
      friend std::ostream& operator << (std::ostream& s, const B& b){
         const A* ptr = &b;
         s << "B";
         s << *ptr;
         return s;
      }
      void foo(){
      }
};

int main(){
   B b;
   std::cout << b;
   return 0;
}


The output is "BA", so exactly what I want. Is there an alternative/better way to solve this problem?
One possible alternative:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

class A {
    public:
        virtual void writeToStream(std::ostream& s) const {
            s << "A";
        }

        virtual void foo() = 0;
};

class B : public A {
    public:
        virtual void writeToStream(std::ostream& s) const {
            s << "B";
            A::writeToStream(s);
        }

        void foo(){
        }
};

std::ostream& operator << (std::ostream& s, const A& a)
{
    a.writeToStream(s);
    return s;
}
Topic archived. No new replies allowed.