Lesson 18 of 24

Virtual Functions and Polymorphism

11 min 35 XP

Through a base-class pointer or reference, a virtual function runs the right derived version at run time (runtime polymorphism). A class with a pure virtual function (= 0) is abstract and can't be instantiated.

Example: edit me and press Run

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.

Give a base class a virtual destructor, or deleting through a base pointer won't clean up the derived part. Interviewers also ask how the vtable works.

Challenge

+35 XP

Write an abstract class Payment with pure virtual double fee(double amount) const, and Upi (fee 0), Card (2%) and NetBanking (flat 10). In main(), read an amount and print each fee with 2 decimals. Input: 1000 Output: UPI: 0.00 Card: 20.00 NetBanking: 10.00

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.