Interview Question
Country: India
Interview Type: Phone Interview
Moreover, if you use the " if ... else " constructs instead of virtual functions, you will have to change your top level processing code whenever a new subtype needs to be handled, while with virtual functions the only thing that needs to be doen is to pass the pointer or reference of the proper instance to the top level function that expects a pointer or reference to the base class.
See the below code that I have created for specifically this comment and see the diffs of conditional and dynamic processing:
class Base{
public:
Base() : class_type(0){};
virtual ~Base() {};
virtual void process(void) {// some processing};
int class_type;
};
class D1 : public Base{
public:
D1() : class_type(1){};
virtual ~D1() {};
virtual void process(void) {// some processing};
int class_type;
};
class D2 : public Base{
public:
D2() : class_type(2){};
virtual ~D2() {};
virtual void process(void) {// some processing};
int class_type;
};
void handle_objects_conditionally(Base *obj)
{
if (obj->type == 0)
//call some Base class specific handler
else if (obj->type == 1)
//call some D1 class specific handler
else if (obj->type == 2)
//call some D2 class specific handler
}
void handle_objects_dynamically(Base *obj)
{
obj->process(); // the proper handler shall be called automagically for you
}
Yes we can. But it's less convenient and much more annoying to do so.
- Anonymous July 25, 2012