I have a class, let's call it A
, it has only one field, aa
. I have another class, B
, which inherits class A
, and instead of having the aa
field, it also has its own field, bb
. Now, I overloaded operator <<
(cout
) for both classes. I tried to use polimorphism, but it seems that polimorphism does not work properly with operators. My code shows me only aa
field when using operator cout
for showing the object obj
.
I mean, do I always need to add the virtual
word to overload the function from the base class in a child class? If so, how should I do the same with operators, operators can't be virtual ...
#include <iostream>
#include <ostream>
using namespace std;
class A
{
protected :
int aa;
public:
A(int aa) {this->aa = aa;}
~A(){}
friend ostream &operator<<(ostream &os, const A& obj);
virtual void show() {cout << "a = " << aa << "\n"; }
};
ostream &operator<<(ostream &os, const A& obj)
{
for(int i=0; i<80; i++)
os << "-";
os << "\n";
os << "a = " << obj.aa << "\n";
for(int i=0; i<80; i++)
os << "-";
os << "\n";
return os;
}
class B : public A
{
private :
int bb;
public:
B(int aa, int bb) : A(aa) {this->bb = bb;}
~B(){}
friend ostream &operator<<(ostream &os, const B& obj);
void show() {cout << "a = " << aa << "\n"; cout << "b = " << bb << "\n";}
};
ostream &operator<<(ostream &os, const B& obj)
{
for(int i=0; i<80; i++)
os << "-";
os << "\n";
os << "a = " << obj.aa << "\n";
os << "b = " << obj.bb << "\n";
for(int i=0; i<80; i++)
os << "-";
os << "\n";
return os;
}
int main()
{
A *obj = new B(2,3);
cout << *obj;
obj->show();
delete obj;
return 0;
}