In C++, assume following class hierarchy:
class BaseClass { };
class ChildClass : public BaseClass { };
Further assume factory classes for these two classes with a common, templated base class:
template<typename T>
class Factory {
public:
virtual T* create() = 0;
};
class BaseClassFactory : public Factory<BaseClass> {
public:
virtual BaseClass* create() {
return new BaseClass(&m_field);
}
private:
SomeClass m_field;
};
class ChildClassFactory : public Factory<ChildClass> {
public:
virtual ChildClass* create() {
return new ChildClass(&m_field);
}
private:
SomeOtherClass m_field; // Different class than SomeClass
};
Note that the size/internal structure of ChildClassFactory
and BaseClassFactory
is different due to their different fields.
Now, if a have an instance of ChildClassFactory
(or Factory<ChildClass>
), can I safely cast it to Factory<BaseClass>
(via reinterpret_cast
)?
Factory<ChildClass>* childFactory = new ChildClassFactory();
// static_cast doesn't work - need to use reinterpret_cast
Factory<BaseClass>* baseFactory = reinterpret_cast<Factory<BaseClass>*>(childFactory);
// Does this work correctly? (i.e. is "cls" of type "ChildClass"?)
BaseClass* cls = baseFactory->create();
I know that you can't always cast templated classes this way, but in this special case a cast should be safe, shouldn't it?
I've tested it with Visual C++ 2010 and it does work. My question now is whether this is portable to other compilers?
Update: Since there has been some confusion let me clarify some more what's (supposed to be) important in my example:
ChildClass
is a child class ofBaseClass
- A user of
Factory<BaseClass>
doesn't know what child class ofBaseClass
will be created. All he knows is thatBaseClass
is created. Factory<T>
has no fields of its own (other than the vtable).Factory::create()
isvirtual