Lesson 18 of 24

Virtual Functions மற்றும் PolymorphismVirtual Functions and Polymorphism

11 min 35 XP

Base class pointer அல்லது reference மூலம் derived object-ஐ அழைக்கும்போது, virtual function சரியான derived version-ஐ இயக்கும் (runtime polymorphism). = 0 என்ற pure virtual function கொண்ட class abstract; அதிலிருந்து object உருவாக்க முடியாது.

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.

Base class-ல் virtual destructor அவசியம்; இல்லையெனில் base pointer மூலம் delete செய்யும்போது derived பகுதி அழியாது. vtable பற்றியும் interview-ல் கேட்பார்கள்.

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

Abstract class Payment: pure virtual double fee(double amount) const. Upi (கட்டணம் 0), Card (2%), NetBanking (பிளாட் 10). main()-ல் amount படித்து மூன்றுக்கும் 2 தசம இடங்களுடன் print செய்யுங்கள். Input: 1000 Output: UPI: 0.00 Card: 20.00 NetBanking: 10.00

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.