#include <iostream>
#include <ostream>

using namespace std;

struct Example
{
    virtual void virtualfunction()=0;
    virtual ~Example() {}
};

struct Implmenetation : Example
{
    bool alive;
    Implmenetation() : alive(true) {}
    void virtualfunction()
    {
        cout << "Implmenetation::virtualfunction alive=" << alive << endl;
    }
    ~Implmenetation()
    {
        alive=false;
        cout << "Implmenetation::~Implmenetation" << endl;
    }
};

struct Forwarder : Example
{
    Example *impl;
    Forwarder(Example *i) : impl(i) {}
    void virtualfunction()
    {
        impl->virtualfunction();
    }
};

void codeIDontControl(Example *ex)
{
     ex->virtualfunction();
     delete ex;
}

void myCode()
{
    Implmenetation impl;

    codeIDontControl(new Forwarder(&impl));
    //do something with ex //doesn't work because ex has been freed
    impl.virtualfunction();
}
int main()
{
    myCode();
}
