Created
November 7, 2016 02:27
-
-
Save eltonvs/7a8f8183c9c196eadc10e4879687b6c9 to your computer and use it in GitHub Desktop.
aaaaaaaaaaaaaaaaaaaaa
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
class Base { | |
public: | |
Base() {} | |
virtual ~Base() = 0; | |
ostream& print(ostream &o) const { | |
o << "id: " << id << "\n"; | |
return o; | |
} | |
protected: | |
int id; | |
}; | |
Base::~Base() {} | |
class Derived: public Base { | |
public: | |
Derived() {} | |
Derived(int i) { | |
Base::id = i, id2 = 123; | |
} | |
~Derived(){} | |
ostream& print(ostream &o) const { | |
o << "id2: " << id2 << "\n"; | |
return o; | |
} | |
private: | |
int id2; | |
}; | |
class Derived2: public Base { | |
public: | |
Derived2() {} | |
~Derived2() {} | |
ostream& print(ostream &o) const { | |
o << "name = " << name << "\n"; | |
return o; | |
} | |
private: | |
string name = "Another type from another class to print"; | |
}; | |
ostream &operator<<(ostream &o, Base *d) { | |
d->print(o); | |
if (Derived *b = dynamic_cast<Derived *>(d)) { | |
return b->print(o); | |
} | |
if (Derived2 *b = dynamic_cast<Derived2 *>(d)) { | |
return b->print(o); | |
} | |
return o; | |
} | |
int main() { | |
Base *b = new Derived(20); | |
Base *c = new Derived2(); | |
cout << b; | |
cout << "--\n"; | |
cout << c; | |
delete b; | |
delete c; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment