#include <string> #include <iostream> using namespace std; class Hoge { public: virtual string to_str(){ return "hoge"; } }; class Piyo : public Hoge { public: virtual string to_str(){ return "piyo"; } }; Hoge *getp() { return new Piyo(); } Hoge get() { Piyo a; return a; } int main() { Hoge *p = getp(); Hoge h = get(); // Piyo h2 = get(); // コンパイルエラー cout << p->to_str() << endl; cout << h.to_str() << endl; // cout << h2.to_str() << endl; return 0; }
$ ./a.out piyo hoge