How would you go about creating a new class that has all the functions of an old class but just does a few things in a few functions differently? I'm looking for it to be as non-intrusive as possible. For ex: imagine you have an all-purpose memory allocator and you want a new memory allocator that does things faster by ignoring a few checks. This new memory allocator has all the same functionality as the original one, except it doesn't check for NULL pointers at the beginning of each function.
I was thinking something along the lines of:
// Rename class MemoryManager to MemoryManagerBase
class MemoryManagerBase;
class MemoryManager : public MemoryManagerBase
class FastMemoryManager : public MemoryManagerBase {
// do something here to change ABase's behavior
};
An actual example of the solution I'm using follows. It uses the CRTP pattern and template policies to do it. Any ideas on how to improve things, do it less intrusively or just different ways to do it would be great:
[source lang='cpp']
class OriginalImplementation {
public:
static void check(void *p) {
if (!p)
std::cout << "Bad Pointer!" << std::endl;
}
};
class FastImplementation {
public:
static void check(void *p){
// noop (does this actually result in a no op?)
}
};
template <class T, class Policies>
class MemoryManagerBase {
public:
void free( T *p ) {
// This used to be if (!p) cout << blah
// Now we replace with the checking policy
Policies::check(p);
// .
// old code
}
void oldFunction() {}
};
template <class T>
class OriginalMemoryManager : public MemoryManagerBase<T, OriginalImplementation> {};
template <class T>
class FastMemoryManager : public MemoryManagerBase<T, FastImplementation> {
private:
void oldFunction(); // Don't want old function available in fast implementation
};
[/source]