#include "Deriveds.hh"
#include "DynObj.hh"
using namespace NoPtr;
class FactoryOne
{
DynObj<Base> owner;
public:
void create(const std::string& type)
{
if (type=="derived1")
owner.acquire(new Derived1);
else if (type=="derived2")
owner.acquire(new Derived2);
else throw std::logic_error("Unknown type");
}
void getObj( DynObj<Base>& newOwned )
{
std::cout << "FactoryOne: giving object" << std::endl;
if (owner.isNull())
throw std::logic_error("No object created");
Base* const tmp = owner.getPtr();
newOwned.acquire( owner );
assert(owner.isNull());
assert(newOwned.getPtr() == tmp);
}
};
void make(FactoryOne& factory, const std::string& type)
{
factory.create(type);
DynObj<Base> mango;
factory.getObj(mango);
assert(mango.isNotNull());
mango().callVirtual();
}
int main()
{
try
{
std::cout << "Using FactoryOne" << std::endl;
FactoryOne factory;
make(factory, "derived1");
make(factory, "derived2");
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
}
}