I have a callback function called as
MyCallBack(int type)
and I have 3 classes B,C and D derived from A having common methods name
Currently my code is like this
MyCallBack(int type){
if(type == 1 ){
B b;
b.perform();
}else if(type==2) {
C c;
c.perform();
}else if(type ==3){
D d;
d.perform();
}
Is there a way I can reduce this code something like
MyCallBack(int type){
Common object(type);
object.perform();
}
Basically, What you need is Polymorphism.
All your classes
B,C,Dshould derive from a Abstract class saySuperBasewith a pure virtual methodperform().Your code should use only a pointer to
SuperBasewhich contains address of actual concrete class object.Once you have this in place, depending on actual type of the object being pointed the method from appropriate class would be called.
The advantage of this method is there is No hardcoded type checking & also flexibility of a loosely coupled design using Open Closed principle.