Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading >> operator for a base class

So I have a base class Animal which has 2 classes inheriting from it, which are cat and dog. Both classes are redefining a pure virtual method speak which just couts "meow" for cat and "woof" for dog. In in my main function I want to be able to do some thing like this:

int main (void) {
  Animal a;
  dog d;

  while (cin  >> a) //is this even possible? would it be cin >> d; instead?
   cout << a << endl;



  return(0);
}

SO this should cout the animals speak function, but how can I go about doing so? Also, I'm confused, if you dont know the type of animal the user is going to cin then how can you determine which speak function to use, would you use a template class?

like image 489
cody Avatar asked Aug 03 '26 13:08

cody


1 Answers

Do something like this in base class:

#include <istream>

using namespace std;

class Animal
{
  friend istream & operator >> ( istream &is, Animal &animal )
  {
    animal.readFromStream(is);
    return is;
  };
protected:
  virtual void readFromStream( istream &is ) = 0;
};

and in derived:

class Dog : public Animal
{
  protected:
    virtual void readFromStream( istream &is )
    {
      // read dog
    };
};
like image 198
Naszta Avatar answered Aug 06 '26 05:08

Naszta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!