There is a class A having the virtual method print() and overloaded operator << defined as a friend function.
#include <iostream>
class A
{
public:
double a1, a2;
A(): a1(10.0), a2(10.0) {}
virtual void print ( std::ostream * o = &std::cout ) const
{
*o << a1<< '\t' << a2 << '\n';
}
friend std::ostream & operator << ( std::ostream & o, const A &aa )
{
o << aa.a1 << '\t' << aa.a2 << '\n';
return o;
}
};
and analogously in derived class B
class B : public A
{
public:
double b1, b2;
B(): A(), b1(20.0), b2(20.0) {}
virtual void print ( std::ostream * o = &std::cout ) const
{
A::print ( o );
*o << b1<< '\t' << b2;
}
friend std::ostream & operator << ( std::ostream & o, const B &bb )
{
o << (A)(bb);
o << bb.b1 << '\t' << bb.b2 << '\n';
return o;
}
};
I have the following questions:
1] Is there any way how to pass a pointer to ostream object with default parameter so as operator << correctly replaces the print() method? This overloading is wrong
friend std::ostream & operator << ( std::ostream * o= &std::cout, const A &aa )
2] I am not sure, if this line calling operator of the parent class A in derived class B is correct?
o << (A)(bb);
3] Is there any better way how to overload operator << without "friend" declaration?
Thanks for your help....
printinoperator<<whenoperator<<can simply callprint? And then you only need oneoperator<<(ostream&, const Base&)and it will work for the complete hierarchy. - pmr