Class: Use of Constructor/Destructor

Page 1

Class Data and its related functions/operations combine to form a class.

Requirements of a class. 1. Class name should represent the object it is made for in a proper way. E.g. student, teacher, account, Date, Time. 2. Class should have wrapper functions (getters and setters) for each data members separately. 3. As the name represents, getters should only be used to just get the data value of data members and setters should only be used to set the value of the data members. 4. The setters can have checks for wrong input values but it’s not a good practice to take input in a setter. 5. Similarly it’s not a good practice to display the value of a data member in a getter. 6. If the class have a display() function to show the values of its data members then it is OK. Otherwise the input and output should be taken in main() function.

Constructors Default constructor. If you are not sure about what values to set in an object at the time of its creation then a default constructor is used to set some default values in data members. E.g. 0 in case of integer data members, 0.0 in case of float and NULL or ‘\0’ in case of string data members. Parametrized constructor. If you are sure about what values to set in an object at the time of its creation then to avoid calling default constructor and then call setters for data members to set their values, a Parametrized constructor is used. The data members are initialized to the values that are passed as parameters in a parametrized constructor. E.g. you have a Date class and you have to set your date of birth in its object. Then observe the following codes: Code 1: int main() { Date dob; dob.setDate(8); dob.setMonth(7); dob.setYear(1994); dob.display(); return 0; } Code 2:


int main() { Date dob(8, 7, 1994); dob.display(); return 0; } In the above code snippets, the second code is better because it requires less work if you have a parametrized constructor in your class. Note: Only one constructor is called in a lifetime of an object. Either it can be default or parametrized. You cannot call constructor by yourself. It is called automatically when object is created.


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.