09-07-2013, 04:20 PM
CONSTRUCTOR, DESTRUCTOR
AIM:
Create a class named weather report that holds a daily weather report with data member’s day_of_month, hightemp, lowtemp, amount_rain and amount_snow. The constructor initializes the fields with default values: 99 for day_of_month, 999 for hightemp,-999 for lowtemp and 0 for amount_rain and amount_snow. Include a function that prompts the user and sets values for each field so that you can override the default values. Write a program that creates a monthly report.
OBJECTIVE:
Understand decomposition of a problem into a number of entities called object and then build data and function around these objects.
THEORY:
Constructors
A constructor is a special member function whose task is to initialize the objects of it's class. This is the first method that is run when an instance of a type is created. A constructor is invoked whenever an object of it's associated class is created. If a class contains a constructor, then an object created by that class will be initialized automatically. We pass data to the constructor by enclosing it in the parentheses following the class name when creating an object
Why you should define a constructor
Uninitialized member fields have garbage in them. This creates the possibility of a serious bug (e.g., an uninitialized pointer, illegal values, inconsistent values ...).
Characteristics of a constructor:
1. They should be declared in the public section
2. They are invoked automatically when the objects are created.
3. They cannot be inherited
4. They cannot be virtual
A constructor is similar to a function, but with the following differences.
1. No return type.
2. No return statement.
Types of Constructor
1. Default Constructor
2. Parameterized constructor
3. Copy constructor
4. Constructor with default arguments
5. Dynamic constructor
PRACTICE ASSIGNMENTS:
1. Create a class named STUDENT that holds student information Stdname, StdRollno, Stdclass, Marks of subject, Percentage. The constructor initializes the fields with default values. Include a function that prompts the user and sets values for each field so that you can override the default values. Write a program that creates a report for ‘N’ number of students.
2. Create a class BANK that holds Account holder information Accname, AccNo, Balance. The constructor initializes the fields with default values. Include a function that prompts the user and sets values for each field so that you can override the default values. Write a program that creates a report for ‘N’ number of Account Holder.
3. Create a class CRICKET that holds Name of Player, Century Scored, Runs Scored, Average, Economy, Wickets, and Catches etc. The constructor initializes the fields with default values. Include a function that prompts the user and sets values for each field so that you can override the default values. Write a program that creates a report for ‘N’ number of Cricketers.