I have two very similar methods. Main difference between them is that they are calling another different method at some point. E.g.:
// method 1
method1(){
// same code for Method1 and Method2 before calling different method
methodA();
// same code for Method1 and Method2 after calling different method
}
// method 2
method2(){
// same code for Method1 and Method2 before calling different method
methodB();
// same code for Method1 and Method2 after calling different method
}
I want to create one method (method
) which will be able to call both different methods (methodA
and methodB
). I guess this should be possible via polymorphism (if I'm wrong correct me please) e.g.:
method(Parent obj){
// same code for Method1 and Method2 before calling different method
obj->methodAB();
// same code for Method1 and Method2 after calling different method
}
class Parent{
public:
virtual int methodAB();
};
// methodA implementation
Class ChildA: public Parent{
public:
int methodAB();
}
// methodB implementation
Class ChildB: public Parent{
public:
int methodAB();
}
actual calling then will be:
Parent *obj = new ChildA; // or Parent *obj = new ChildB;
method1(obj)
delete obj;
But there is one serious problem: In my case methodA()
and methodB()
takes as argument different types, so my situation is actually:
method1(obj_type1){
// same code for Method1 and Method2 before calling different method
methodA(obj_type1);
// same code for Method1 and Method2 after calling different method
}
method2(obj_type2){
// same code for Method1 and Method2 before calling different method
methodB(obj_type2);
// same code for Method1 and Method2 after calling different method
}
Is it possible to implemented virtual function in derived classes with different types as arguments or is there any another elegant solution for this problem?