Skip to content

Instantly share code, notes, and snippets.

@eltonvs
Created November 7, 2016 02:27
Show Gist options
  • Save eltonvs/7a8f8183c9c196eadc10e4879687b6c9 to your computer and use it in GitHub Desktop.
Save eltonvs/7a8f8183c9c196eadc10e4879687b6c9 to your computer and use it in GitHub Desktop.
aaaaaaaaaaaaaaaaaaaaa
#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