I have two classes, base and derived. In main I have a vector which is *base
type and contains one base object and one derived object. I have overloaded output operator for both classes, but when I print the vector for derived class, base output operator is called although I have overloaded it separately. What should I change in my program to change output from:
12
30
to
12
30 31
?
This is the code:
#include <iostream>
#include <vector>
using namespace std;
class base {
int x;
public:
base(int _x) : x(_x) {}
friend ostream& operator<<(ostream& out, base obj) {
return out << obj.x;
}
};
class derived : public base {
int y;
public:
derived(int _x, int _y) : base(_x), y(_y) {}
friend ostream& operator<<(ostream& out, derived obj) {
return out << (base) obj << ' ' << obj.y;
}
};
int main() {
vector<base*> vec;
base* a = new base(12);
derived* b = new derived(30,31);
vec.push_back(a);
vec.push_back(b);
for (auto p: vec) cout << *p << '\n';
}