Re: Correct vesion (Re: Clone an object with an abstract base class)
On 16/10/2014 17:53, Paavo Helde wrote:
JiiPee <no@notvalid.com> wrote in news:2PK%v.461970$177.56098@fx04.am4:
Can you show me a simple code example where the clone can only be done
by virtual and not factory method?
Here it goes. Assume that the build process checks out and builds
projects one-by one, in the order specified somewhere else (I have used
such a process for many years in the past), to avoid any fancy ideas of
including b.h in the base library (which would by all wrong conceptually
anyway).
And why does this factory version of it not work (for example inserting
the factory in main.cpp)? I have not compiled, but seems like it might
work:
// base library (DLL)
// a.h
class A {
public:
virtual ~A() {}
};
// -------------------------------------
// extension library (DLL) - link to base library
// b.h
//#include <BaseLibrary/a.h>
class B: public A {
public:
};
// b.cpp
// -------------------------------------
// main program - link to base library and extension library
// main.cpp
//#include <BaseLibrary/a.h>
//#include <Extensionlibrary/b.h>
A* foo(A *x) {
B *b1 = nullptr;
if( typeid(*x) == typeid(A) )
b1 = new A(*(dynamic_cast<A*>(b1)));
else if( typeid(*x) == typeid(B) )
b1 = new B(*(dynamic_cast<B*>(b1)));
return b1;
}
int main() {
A* x = new B();
foo(x);
delete x;
}