0

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 2
    In this particular case you might want to follow [this suggestion](https://stackoverflow.com/questions/11905648/overloading-with-inhertiance-and-polymorphism) and have a single `operator<<` that takes a `const A&` and invokes a virtual helper method – Nathan Pierson Nov 16 '21 at 18:42
  • TL;DR of that dupe: make a polymorphic `print()` or `toString()` function that you call in the `operator<<()`. – scohe001 Nov 16 '21 at 18:43

1 Answers1

2

Declare a virtual function in the base class, like for example:

virtual std::ostream & out( std::ostream &os ) const;

The function may be protected.

And then override it in derived classes.

Then, in the friend operator<<, call the function.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335