There are basically two ways to provide your own interface for a third party class.
1. Inheritance:
This wouldn't work, as you need to include the header file in your own header file, and you wish to avoid this.
2. Using delegates:
Your own class creates an instance of the library class on the heap and only stores its pointer. Here's a simple example:
class foo {
public:
void doSomething();
void doSomeOtherThing();
};
#include "foo.h"
class bar {
public:
void process(foo* f);
};
Your delegate class declarations:
class foo; class myfoo {
foo* foo_delegate; friend class mybar; public:
myfoo(); ~myfoo(); void doSomething();
void doSomeOtherThing();
};
class bar;
#include "myfoo.h"
class mybar {
bar* bar_delegate;
public:
mybar();
~mybar();
void process(myfoo* mf);
};
And your delegate implementation:
#include "myfoo.h"
#include "foo.h"
myfoo::myfoo() {
foo_delegate = new foo; }
myfoo::~myfoo() {
delete foo_delegate; }
void myfoo::doSomething() {
foo_delegate->doSomething();
}
void myfoo::doSomeOtherThing() {
foo_delegate->doSomeOtherThing();
}
#include "mybar.h"
#include "bar.h"
mybar::mybar() {
bar_delegate = new bar;
}
mybar::~mybar() {
delete bar_delegate;
}
void mybar::process(myfoo* mf) {
foo* f = mf->foo_delegate; bar_delegate->process(f);
}
Now you can use your class delegates
myfoo
and
mybar
exactly like you would use the original classes
foo
and
bar
. And you have the option to change any aspect of this interface, within your own implementation. The only trace of the original classes are the delegate pointers which do not require including the corresponding headers in your own header files.
PS: the method
mybar::process
shows how you can delegate any function that expects argument types of the hidden library. You need to be careful that your delegates may need access to the delegate pointers inside other classes, that is the reason for the
friend
declaration in class
myfoo
.