How can make this vector of pointers and then print de Derived1 object and Derived2 object properly ?
Even if I included the "<<" operator in derived classes , it seems that the base class operator is used . And I cannot make the operators virtual because they are not members of the class , they are friend .
What can I do to make the program take the "<<" operator from Derived1 class or Derived2 class and furthermore, print the Base class things, by using :
out << (Base&)temp;
in my operator's definition .
#include<iostream>
#include<fstream>
using namespace std;
class Base {
private:
int base;
public:
Base() :base(10){}
friend ostream& operator<<(ostream& out, const Base& temp)
{
out << "======== BASE ========" << endl;
out << temp.base << endl;
out << "======== BASE ========" << endl;
return out;
}
friend ofstream& operator<<(ofstream& out, const Base& temp)
{
out << "======== BASE ========" << endl;
out << temp.base << endl;
out << "======== BASE ========" << endl;
return out;
}
};
class Derived1 :public Base {
private :
int derived1;
public:
Derived1() :derived1(5){}
friend ostream& operator<<(ostream& out, const Derived1& temp)
{
out << (Base&)temp;
out << "======== DERIVED1 ========" << endl;
out << temp.derived1 << endl;
out << "======== DERIVED1 ========" << endl;
return out;
}
friend ofstream& operator<<(ofstream& out, const Derived1& temp)
{
out << (Base&)temp;
out << "======== DERIVED1 ========" << endl;
out << temp.derived1 << endl;
out << "======== DERIVED1 ========" << endl;
return out;
}
};
class Derived2 :public Base {
private:
int derived2;
public:
Derived2() :derived2(5) {}
friend ostream& operator<<(ostream& out, const Derived2& temp)
{
out << (Base&)temp;
out << "======== DERIVED2 ========" << endl;
out << temp.derived2 << endl;
out << "======== DERIVED2 ========" << endl;
return out;
}
friend ofstream& operator<<(ofstream& out, const Derived2& temp)
{
out << (Base&)temp;
out << "======== DERIVED2 ========" << endl;
out << temp.derived2 << endl;
out << "======== DERIVED2 ========" << endl;
return out;
}
};
void main()
{
Derived1 d1;
Derived2 d2;
Base* v[2];
v[0] = &d1;
v[1] = &d2;
cout << *v[0] << endl;
ofstream f("fis.txt");
f << *v[0];
}