Recently I attended an interview. The interviewer and I were talking about virtual functions in c++. I explained all the concept of virtual function and how It works using vtable
and vptr
. He was ok with my explanation. At the end of the conversation about virtual function, he asked me a question that why should we call the derived class function using a base class pointer?
For Ex.,
Shape
is a base class
. Circle
and Square
are derived classes
inherited from the base class 'Shape
'. Defined method area()
is the virtual function.
Shape *basePtr = new Circle();
baseptr->area();
He asked me why are we using the base pointer to call the derived class function here? Why don't we create a derived class object and through the object we can call the derived class method?
I told him, we can create a handler function as the parameter of the function always be as base class pointer
. So that we can simply call the derived class object(s) to the handler function
for the use of Generic implementation.
Also, we can store the derived class objects into a vector of the base class pointer and we can access the derived class methods by iterating the vector. Through this, we can set up an order to do the task sequentially.
But he just smiled and shook his head. Why I am posting this question here is what is the exact answer to the question? or My answers of enough to explain the question?