Please check the line(s) of code after the comments '//this is the line of code in question... '.
I want to know if this is the proper way to use the std::ostream operator<< in multi-inheritance? Basically I want the derived object(dog) to call the base object's std::ostream operators without hard-coding it....Please note the program works, I'm just looking for a verification. Is this the proper way to use the std::ostream operator in this program?
#include <iostream>
class animal
{
public:
animal(const char *name):itsname(name) {}
virtual ~animal() {}
friend std::ostream& operator<<(std::ostream & out, const animal & rhs);
protected:
const char *itsname;
};
class mammal:public animal
{
public:
mammal(const char *name, unsigned long val):animal(name), itsweight(val) {}
virtual ~mammal() {}
friend std::ostream& operator<<(std::ostream & out, const mammal & rhs);
protected:
unsigned long itsweight;
};
class dog:public mammal
{
public:
dog(const char *name, unsigned long weight, unsigned long age):mammal(name, weight), itsage(age) {}
virtual ~dog() {}
friend std::ostream& operator<<(std::ostream & out, const dog & rhs);
protected:
unsigned long itsage;
};
std::ostream& operator<<(std::ostream & out, const animal & rhs)
{
//this is the line of code in question...
out<<"animal's name->"<<rhs.itsname;
return out;
}
std::ostream& operator<<(std::ostream & out, const mammal & rhs)
{
//this is the line of code in question...
out<<*dynamic_cast<const animal*>(&rhs)<<" - "<<"mammal's weight->"<<rhs.itsweight;
return out;
}
std::ostream& operator<<(std::ostream & out, const dog & rhs)
{
//this is the line of code in question...
out<<*dynamic_cast<const mammal*>(&rhs)<<" - "<<"dog's age->"<<rhs.itsage;
return out;
}
int main(int argc, char**argv)
{
dog mydog("vicious dog woof", 4321, 34);
std::cout<<mydog<<"\n";
return 0;
}
Program's output:
animal's name->vicious dog woof - mammal's weight->4321 - dog's age->34