Say I've got the following code:
class A {};
class B : public A {
public:
explicit B(string s) {}
friend ostream &operator<<(ostream &out, const B &b) {
out << "b";
return out;
}
};
class C : public A {
public:
explicit C(int i) {}
friend ostream &operator<<(ostream &out, const C &c) {
out << "c";
return out;
}
};
Then, I have a function like this:
A s(int i) {
if (i == 0)
return dynamic_cast<B>(B("hello world")); // first try
else {
return C(12); // second try
}
}
In main, I write the followings:
#include <iostream>
using namespace std;
int main() {
cout << *(s(0)) << endl; // should print "b"
cout << *(s(1)) << endl; // should print "c"
return 0;
}
How can I do it? (any answer should work for C++14)
Thanks in advanced.