Lab P13 β Demonstrate run-time polymorphism.
Aim
Aim: Demonstrate run-time polymorphism via virtual functions.
Theory
Demonstrate run-time polymorphism via virtual functions.
C++ Program
#include
using namespace std;
class Base { public: virtual void show(){ cout<<"Base\n"; } };
class Derived : public Base { public: void show(){ cout<<"Derived\n"; } };
int main(){ Base* p=new Derived(); p->show(); delete p; return 0; } Expected Output
DerivedExplanation
- Base* points to Derived object.
- virtual ensures Derived::show called.
Viva / Important Questions
Short Questions
- What is run-time polymorphism?
- Role of virtual keyword?
Long Questions
- Explain the program in detail.
- Discuss key concepts demonstrated.
MCQ Practice
1. Run-time polymorphism via:
- Virtual functions
- Overloading
- Templates
- None
Answer: Virtual functions.
2. Resolved at:
- Run time
- Compile time
- Link time
- Never
Answer: Run time.
3. Uses:
- vtable
- Stack
- Heap
- None
Answer: vtable.
4. Base pointer to derived calls:
- Derived version
- Base version
- Both
- None
Answer: Derived version.
5. Also called:
- Dynamic binding
- Static binding
- Late none
- None
Answer: Dynamic binding.
Quick Revision
- Virtual functions enable runtime polymorphism.
- Dynamic binding via vtable.