I don't know exactly why the following code compiles and works (it works well).
#include <iostream>
struct Base
{
virtual std::ostream& display(std::ostream& os) const = 0;
friend std::ostream& operator<<(std::ostream& lhs, const Base& rhs)
{
return rhs.display(lhs);
}
};
struct A: Base
{
virtual std::ostream& display(std::ostream& os) const
{
return os << "A" << std::endl;
}
};
struct B: A
{
virtual std::ostream& display(std::ostream& os) const
{
return os << "B" << std::endl;
}
};
int main()
{
A a;
std::cout << a << std::endl;
B b;
std::cout << b << std::endl;
}
I am defining the operator<<
only once inside the Base
class, which calls the pure virtual display
function. This scheme is usually used to avoid re-writing operator<<
in the derived classes, i.e. define it only once in the base class then use virtual dispatch with another function (in my case, display()
).
See Live on Coliru
Can you explain why I am able to call a pure virtual function inside the Base
class in the implementation of friend std::ostream& operator<<(...)
? I thought this shouldn't be possible.