I've got some code that uses a somewhat sneaky cast from a base class type to a child class type, where the child class type is specified as a template parameter. I'm assuming since the base class declares no data members and is zero-sized, the base class pointer address will be the same as the child, and the cast will succeed. So far the code runs correctly.
Here's a simplified version of what I'm doing:
template <class RangeT>
struct CppIterator {
CppIterator(const RangeT& range) { ... }
// ... methods calling RangeT's members
};
// Base class, provides begin() / end() methods.
template<class RangeT>
struct CppIterableBase {
CppIterator<RangeT> begin() {
return CppIterator<RangeT>( *(RangeT*)this ); // Is this safe?
}
CppIterator<RangeT> end() { ... }
};
struct MyRange : CppIterableBase<MyRange> {
// ...
};
My question is basically - is the code kosher? Will a base pointer always equate to a child pointer if the base is empty? Is it implementation-dependent? Will I run into trouble later on?
It solves my problem nicely but I'm a little dubious.