I am currently trying to deliver more than one implementation of an header file. I tried doing this like this:
// A.h:
class A {
public:
A();
~A();
bool method1();
bool method2();
}
// A.cpp:
A::A() {
}
A::~A() {
}
bool A::method1() {
}
bool A::method2() {
}
// B.h
class B : public A {
public B();
public ~B();
bool method1();
bool method2();
}
// B.cpp
B::B() {
}
B::~B() {
}
bool B::method1() {
// actual code I want to use
}
bool B::method2() {
// actual code I want to use
}
// AFactory.h
#define USE_B 10
#define USE_C 20
#define IMPL USE_B
class A;
class AFactory {
public:
static A *getImplementation();
}
// AFactory.cpp
A *AFactory::getImplementation() {
#if IMPL == USE_B
return new B();
#elif IMPL == USE_C
return new C();
#else
return NULL;
#endif
}
// Test.cpp
int main () {
A *test = AFactory::getImplementation();
test->method1();
test->method2();
}
The idea was, to deliver more than one implementation of the class A, which could be switched by simply changing the value of the define IMPL. The problem is, that the methods from the actual used implementation B are never called. The methods from the base class A are called instead. I tried to remove the A.cpp completly from the build, since it’s never used or rather should never be used, but then it won’t build, telling me, that I have undefined references in my test code.
If you want to override these methods, you use the
virtualkeyword.