Lesson 18 of 24

Virtual Functions, Polymorphism

11 min 35 XP

Base-class pointer അല്ലെങ്കിൽ reference വഴി virtual function run time-ൽ ശരിയായ derived version പ്രവർത്തിപ്പിക്കുന്നു (runtime polymorphism). Pure virtual function (= 0) ഉള്ള class abstract ആണ്, അതിന്റെ object ഉണ്ടാക്കാനാവില്ല.

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 എങ്ങനെ പ്രവർത്തിക്കുന്നുവെന്നും interviewers ചോദിക്കും.

Challenge

+35 XP

Pure virtual double fee(double amount) const ഉള്ള abstract class Payment-ഉം Upi (fee 0), Card (2%), NetBanking (flat 10) എന്നിവയും എഴുതൂ. main()-ൽ ഒരു amount വായിച്ച് ഓരോ fee-യും 2 ദശാംശത്തോടെ print ചെയ്യൂ. 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.