I must write a program which in one of its function will return a derived class via an abstract base class, so when the class being returned to the main may access the derived class virtual methods.
Please keep in mind that I can't change anything in the main program since I am not the one writing it.
#include<iostream>
using namespace std;
class A
{
private:
public:
virtual void DoIt(void)=0;
A(void){};
~A(void){};
};
class B:
public A
{
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 I try to run this the last line breaks the build saying that DoIt
is a pure virtual function call.
any ideas?
You are returning a reference to a local variable which is destroyed when the call to in returnvalue
is complete. Instead try the following:
A &returnValue(void) {
return *(new B);
}
int main() {
A& item = returnValue();
item.DoIt();
}
A better solution is to return a smart pointer and let the people maintaining the main function take responsibility for the lifetime of the object returned by returnvalue
:
#include <memory>
...
std::unique_ptr<A> returnValue(void) {
return std::unique_ptr<A>(new B);
}
int main() {
auto item = returnValue();
item->DoIt();
}