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 हिस्सा साफ़ नहीं होगा। Interviewers यह भी पूछते हैं कि vtable कैसे काम करता है।

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.