Lesson 16 of 24

Constructors और Destructors

10 min 30 XP

Object बनने पर constructor चलता है; नष्ट होने पर destructor (~ClassName) चलता है। Fields सेट करने का सबसे अच्छा तरीका initializer list (: name(n)) है। static member सभी objects में साझा होता है।

Example: edit me and press Run

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

Block खत्म होते ही b का destructor अपने-आप चलता है। यह RAII है, यानी resources को object के जीवनकाल से बाँधना, और यह C++ का सबसे महत्वपूर्ण विचार है।

Challenge

+30 XP

class Time लिखें जिसमें constructor Time(int h, int m, int s), समय जोड़ने वाला add(int seconds) (24 घंटे पर घूम जाए) और "HH:MM:SS" को दो-दो अंकों में print करने वाला print() हो। main() में h m s और जोड़ने वाले seconds पढ़ें, फिर print करें। Input: 23 59 30 45 Output: 00:00:15

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