c++ - returning a derived class object through a pointer of its abstract base class -
i must write program in 1 of function return derived class via abstract base class, when class being returned main may access derived class virtual methods.
please keep in mind can't change in main program since not 1 writing it.
#include<iostream> using namespace std; class { private: public: virtual void doit(void)=0; a(void){}; ~a(void){}; }; class b: public { private: int num; public: virtual void doit(void){num=7;cout<<"its done";}; b(void){}; ~b(void){}; }; a& returnvalue(void) { b item; return item; } void main() { a& item=returnvalue(); item.doit(); }
when try run last line breaks build saying doit
pure virtual function call. ideas?
you returning reference local variable destroyed when call in returnvalue
complete. instead try following:
a &returnvalue(void) { return *(new b); } int main() { a& item = returnvalue(); item.doit(); }
a better solution return smart pointer , let people maintaining main function take responsibility lifetime of object returned returnvalue
:
#include <memory> ... std::unique_ptr<a> returnvalue(void) { return std::unique_ptr<a>(new b); } int main() { auto item = returnvalue(); item->doit(); }
Comments
Post a Comment