Lesson 16 of 24

Constructors மற்றும் DestructorsConstructors and Destructors

10 min 30 XP

Constructor object உருவாகும்போது இயங்கும்; destructor (~ClassName) object அழியும்போது இயங்கும். Initializer list (: name(n)) fields-ஐ அமைக்கும் சிறந்த வழி. static member எல்லா objects-க்கும் பொதுவானது.

A constructor runs when an object is created; the destructor (~ClassName) runs when it is destroyed. An initializer list (: name(n)) is the best way to set fields. A static member is shared by all 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++-ன் மிக முக்கியமான கொள்கை.

b's destructor runs automatically when the block ends. This is RAII, tying resources to an object's lifetime, and it is the most important idea in C++.

Challenge

+30 XP

Time class: constructor Time(int h, int m, int s); method add(int seconds) நேரத்தைக் கூட்டும் (24 மணி நேரம் சுழற்சி); method print() "HH:MM:SS" (இரண்டு இலக்கங்கள்). main()-ல் h m s மற்றும் கூட்ட வேண்டிய seconds படித்து print செய்யுங்கள். Input: 23 59 30 45 Output: 00:00:15

Write class Time with a constructor Time(int h, int m, int s), add(int seconds) that adds time (wrapping at 24 hours) and print() that prints "HH:MM:SS" with two digits each. In main(), read h m s and the seconds to add, then 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.