Problem Statement
Write a program that calculates the distance in terms of feet and inches.
Preliminary Analysis
An object must be directly representable using a single type A distance has two attributes: Feet (integer) Inches (float) When an object cannot be directly represented by any of the available types, build a class!
Building Classes
Begin by defining variables to store the attributes of the object being represented (a distance) int feet; float inches;
Building Classes
class distance { private: int feet; float inches; public: void getData() { cout<<"Enter Feet\n"; cin>>feet; cout<<"Enter Inches\n"; cin>>inches; } void showData() { cout<<feet<<" feet and "<<inches<<"inches\n"; } };
Declaring this class does not allocate memory for a Distance It just tells the compiler what Distance is and what are its attributes
Data Hiding
Hiding data from parts of the program that do not need to access it Classes have a public section and a private section Items (data or functions) declared in the public section are accessible to users of the class i.e., they can be accessed from outside the class Items declared in the private section are inaccessible to users of the class i.e., they can only be accessed from within the class Data members should go in the private section, to prevent programmers from writing programs that access data members directly All class members are private by default
Defining an Object
A programmer can now write:
Distance d1; and object d1 can be visualized as follows: d1
feet inches
The data members feet and inches within Distance are uninitialized
Problem
At present, a Distance declaration: Distance d1; leaves Distances data members uninitialized To auto-initialize them to a default value, we can use a special function called a constructor
Constructors
A constructor function is a class member function whose task is to initialize the class data members Since it returns nothing, a constructor has no return type (not even void) The name of a constructor is always the name of the class (in this case Distance())
Distance () { feet=0; inches=0.0; }
Contd
Since they specify the first thing a user of the class needs to know (i.e., how to define class objects), constructor prototypes are usually the first function members listed in the public section of the class
Object Definitions
A programmer can now write:
Distance d1; and object d1 can be visualized as follows: d1
feet inches
0
0.0
#include<iostream.h> class Distance { private: int feet; float inches; public: Distance () { feet=0; inches=0.0; }
void getData() { cout<<"Enter Feet\n"; cin>>feet; cout<<"Enter Inches\n"; cin>>inches; }
Problem 2
At present, we can only initialize Distance to a default value: Distance d1; We have no means of initializing Distance to any other value. To initialize Distance to a particular value (e.g., 10,3.5), we can overload the constructor with a second definition
Constructor 2 Definition
To overload the constructor, we just provide a second definition (and prototype) that differs from all other constructors in at least one parameter To initialize the data members of our class, this second constructor must receive the initial values via its parameters The same name can be used to define different functions, provided the signature (the list of the parameter types) of each function is different Distance (int ft, float in) { feet=ft; inches=in; }
Object Definitions
A programmer can now write:
d2
feet inches
10 3.9
The compiler uses the number of arguments in a declaration to decide which constructor to use in initializing an object
d1.getData(); d1.showData();
}
Distance () : feet (0), inches (0) { } Distance (int ft, float in) : feet (ft), inches (in) { }
No-Argument Constructor
If you dont explicitly define any constructors, the compiler automatically generates a default constructor that takes no arguments So in case you do not define any constructors and simply create a Distance object
Distance d1;
The compiler will call a default constructor which does not, however, assign any values to the data members But once youve defined even one kind of constructor (may be a 2-arg constructor),the compiler will no longer create a default no-argument constructor for you
No-Argument Constructor
E.g., if I remove the following from my class declaration Distance () { feet=0; inches=0.0; } And then try to execute the following in main()
Default Arguments/Parameters
Any C++ function can provide default values for its input function arguments If a value is not specified in a function call, the default value is assigned and sent to the called function To clear up any confusion to the compiler, a rule is enforced when using default values and multiple arguments All arguments to the right of an argument with a default value must be specified In other words, their can be no "holes" in your default parameter list
This rule helps the compiler determine which arguments to assign values to in a function call
void main () { cout<<"Enter a number to find its Square\n\n"; int num; cin>>num; cout<<endl; cout<<num<<" suare = "<<square(num); cout<<endl; cout<<endl; }
We can combine two functions (constructor without parameters and constructor with parameters) using default parameters of C++
No-argument constructor initializes data members to constant values. Multi-argument constructor initializes to values passed as arguments. Another way- initialize an object with an other object of the same type no need for special constructor- default copy constructor: a one-argument constructor, whose argument is the object of the same class as constructor.
Activity
Create a class date with member functions getDate() and printDate(). Define the constructors
Class Destructors
Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed Same name as the class but preceded by a tilde (~) Has no arguments and no return type
class X { private: int a; public: X():a(0){} // Constructor for class X ~X(){} // Destructor for class X };
class Distance { public: int feet; float inches; public: Distance (int ft=0, float in=0.0) { feet=ft; inches=in; } void getData() { cout<<"Enter Feet\n; cin>>feet; cout<<"Enter Inches\n; cin>>inches; } void showData() { cout<<feet<<" feet and "<<inches<<"inches\n;} void add_dist(Distance, Distance); };
void Distance :: add_dist(Distance d1, Distance d2) { inches = d1.inches + d2.inches; if (inches >= 12.0) { inches -= 12.0; feet++; } feet += d1.feet + d2.feet; } void main() { Distance d1 (8, 7.0); d1.showData(); Distance d2(5,3.9); d2.showData(); cout<<"The sum of d1 & d2 is"; Distance d3; d3.add_dist(d1,d2); d3.showData();}
Distance Distance :: add_dist(Distance d2) { Distance temp; temp.inches = inches + d2.inches; if (temp.inches >= 12.0) { temp.inches -= 12.0; temp.feet =1; } temp.feet += feet + d2.feet; return temp;
int main() { Distance dist1,dist3; Distance dist2(11,6.5); dist1.getdist(); //from user dist3 = dist1.add_dist(dist2); return 0; }
Recommended Reading
Robert Lafore, Chapter 6: Objects and Classes Dietel & Dietel, Chapter 9