As the title suggests, I am trying to invoke overloaded operators in derived classes, while all of the objects are in a collection of type "pointer to base". In this case, std::array<A*, #>
. I think that the code examples will make my situation more clear.
classes.h:
#include <iostream>
class A
{
friend std::ostream& operator<<(std::ostream& os,const A& a){
os << "I am a A!";
return os;
}
};
class B : public A{
friend std::ostream& operator<<(std::ostream& os,const B& b){
os << "I am a B!";
return os;
}
};
class C: public A{
friend std::ostream& operator<<(std::ostream& os,const C& c){
os << "I am a C!";
return os;
}
};
main.cpp:
#include <iostream>
#include <array>
#include "classes.h"
int main(){
std::array<A*, 2> arr;
arr[0] = new B;
arr[1] = new C;
std::cout << *arr[0] << "\n";
std::cout << *arr[1] << "\n";
return 0;
}
The output of this program is:
I am a A!
I am a A!
But I would like it to be:
I am a B!
I am a C!
Is there an elegant way of doing this?