Respected Sir!
i should tell you that what i know and what i don\'t know about the asked question so that you can address the weak area of my understanding.
Since show is declared virtual in the person class, the compiler will not hard-code the method call like it would do for a non-virtual method, it will instead compile a lookup in the V-table in order to retrieve the right function.
So ptr->show() will be compiled as ptr->vtable['show']() which means "search the function pointer that corresponds to method show and execute it".
Since at runtime, ptr points to an object of class teacher, the vtable slot for show contains a pointer to the method show in the class teacher. That is why the right method is executed.
Actually, lookup in the V-table is not done using strings but using numeric method identifiers in order to be as fast as possible.