Y
yan
Hi, everybody. I'm new to this great forum, so hello!
I start with a problem of my project.
I have an Abstract Base Class used as base class for differentes
Derived classes. The derived classes must able to set the behavior
af a function f() at run-time. I want use the same function behavior
also in Another Class, but without using inheritance because
Another Class not extend Base Class.
I have used a function pointer and static members function declared
in Base Class for differentes implementation of the function f().
Is correct? or is convenient to define a new class to share common
functionalities between Derived and Another class?
Here is the example code.
I start with a problem of my project.
I have an Abstract Base Class used as base class for differentes
Derived classes. The derived classes must able to set the behavior
af a function f() at run-time. I want use the same function behavior
also in Another Class, but without using inheritance because
Another Class not extend Base Class.
I have used a function pointer and static members function declared
in Base Class for differentes implementation of the function f().
Is correct? or is convenient to define a new class to share common
functionalities between Derived and Another class?
Here is the example code.
Code:
class AbstractBaseClass {
public:
virtual int f(int a, int b) = 0;
virtual void setImplementation(int implType) = 0;
static int fImplementationOne(int a, int b) {
return a+b;
}
static int fImplementationTwo(int a, int b) {
return a-b;
}
};
class DerivedClass : public AbstractBaseClass {
public:
DerivedClass(int implType) {
setImplementation(implType);
}
void setImplementation(int implType) {
if (implType == 0)
_f = &AbstractBaseClass::fImplementationOne;
else
_f = &AbstractBaseClass::fImplementationTwo;
}
int f(int a, int b) {
return _f(a, b);
}
private:
int (*_f)(int a, int b);
};
class AnotherClass {
public:
AnotherClass() {
_f = &AbstractBaseClass::fImplementationOne;
}
private:
int (*_f)(int a, int b);
};
int main()
{
AnotherClass a;
AbstractBaseClass *c = new DerivedClass(0);
cout << c->f(10,3) << '\n';
c->setImplementation(1);
cout << c->f(10,3) << '\n';
}