EDIT: the code had a typo, now it compiles but I am still not getting the output I want.
I am attempting to overload the stream operator for std::cout
, std::fstream
, etc, but I am not being able to handle polymorphism properly: I am not able to get the output I want to see.
I would like the subclasses to show the content of the superclass and then its content, while the superclass to show only its content.
This can be achieved by introducing a new function print_only_base()
in the Base
function, but I suspect that I can make the code working even without adding a new function.
What I want to get
I have a base class which has some attributes that I want to be showed on screen when I do
Base base;
std::cout << base;
There are two classes, A
and B
which inherits from Base
. Base
is a polymorphic class and A
and B
are showing different output when streamed.
I want an object of class Base
to show only its output, while an object of class A
(the same for B
) to show first the output itself if seen as an instance of Base
and then the output of itself seen as A
(or B
).
Below the code I write the output I would expect and my (not working) attempt.
#include <iostream>
class Base {
virtual std::ostream & print(std::ostream stream) const {
stream << "Base class output\n";
return stream;
}
public:
friend std::ostream & operator<<(std::ostream & stream, const Base & obj) {
return obj.print(stream);
}
virtual ~Base() {}
};
class A : public Base {
std::ostream & print(std::ostream & stream) const {
stream << "foo = " << foo << "\n";
return stream;
}
int foo = 0;
public:
friend std::ostream & operator<<(std::ostream & stream, const A & obj) {
// here I would like to call the base class for printing, but I would enter in an infinite loop
return obj.print(stream);
}
~A() {}
};
class B : public Base {
std::ostream & print(std::ostream & stream) const {
stream << "bar = " << bar << "\n";
return stream;
}
int bar = 0;
public:
friend std::ostream & operator<<(std::ostream & stream, const B & obj) {
// here I would like to call the base class for printing, but I would enter in an infinite loop
return obj.print(stream);
}
~B() {}
};
Main function:
int main(int argc, char * argv[]) {
Base * base = new Base();
A * a = new A();
B * b = new B();
Base * a_inside = dynamic_cast<Base *>(a);
std::cout << *base << "\n";
std::cout << *a << "\n";
std::cout << *b << "\n";
std::cout << *a_inside << "\n";
delete base;
delete a;
delete b;
/* output I want to get
Base class output
Base class output
foo = 0
Base class output
bar = 0
Base class output
foo = 0
*/
return 0;
}
How can I get the desired behaviour?