02 Objects and Classes
02 Objects and Classes
CLASSES
data 1
data 2
data 3
Functions
func 1 ()
func 2 ()
func 3 ()
• This program contains a class and two objects of that class. Although it’s simple, the program
demonstrates the syntax and general features of classes in C++.
#include <iostream>
using namespace std;
class simpleclass
{
private:
int somedata;
public:
void setdata (int d)
{ somedata = d; }
void showdata()
{ cout << "Data is " << somedata << "\n"; }
};
#include <iostream>
using namespace std; • The class simpleclass defined
in this program contains one
class simpleclass data item (somedata) and two
{ member functions (setdata
private: and showdata).
int somedata;
• The two member functions
provide the only access to the
public: data item somedata from
void setdata (int d) outside the class.
{ somedata = d; }
• The first member function sets
void showdata() a value for the data item, and
{ cout << "Data is " << somedata << "\n"; } the second displays the value.
};
main()
{
simpleclass s1, s2;
The output of this
program will be:
s1.setdata(1066);
s2.setdata(1776);
Data is 1066
Data is 1776
s1.showdata();
s2.showdata();
}
• The following is the definition (sometimes called a specifier) for the class
simpleclass:
class simpleclass
{
private:
int somedata;
public:
void setdata (int d)
{ somedata = d; }
void showdata()
{ cout << "Data is " << somedata << "\n"; }
};
class simpleclass
{ The setdata() function
private: accepts a value as a
int somedata; parameter and sets
the somedata variable
public: to this value.
void setdata (int d)
{ somedata = d; } The showdata()
function displays the
void showdata() value stored in
{ cout << "Data is " << somedata << "\n"; } somedata.
};
• Now that the class is defined, main() can now make use of it.
main()
{
simpleclass s1, s2;
s1.setdata(1066);
s2.setdata(1776);
s1.showdata();
s2.showdata();
}
• At this point, there are now two objects called s1 and s2.
Each has its own somedata variable and the two functions
setdata() and showdata().
Object s1 Object s2
Data Data
somedata somedata
Functions Functions
setdata () setdata ()
showdata () showdata ()
main()
{ To use a member
function, the dot
simpleclass s1, s2; operator (the period)
connects the object
s1.setdata(1066); name and the member
s2.setdata(1776); function.
s1.showdata(); s2.setdata(1776);
main()
{ Similarly, the following
simpleclass s1, s2; two calls to the
showdata() function will
s1.setdata(1066); cause the two objects to
s2.setdata(1776); display their values:
s1.showdata(); s1.showdata();
s2.showdata(); s2.showdata();
}
• Usually the data within a class is private and the functions are public. This is a
result of the way classes are used.
• The data is hidden so it will be safe from accidental manipulation, while the
functions that operate on the data are public so they can be accessed from
outside the class.
• If the statement
s1.somedata = 1000;
was included in main(), this would have resulted in an error since somedata was
defined as private.
However, the same statement would have been accepted if somedata was
defined as public.
s1.showdata();
#include <iostream>
using namespace std;
class part
{
private: This program features the class part.
int modelnumber; Instead of one data item, as
int partnumber; simpleclass had, this class has three:
modelnumber, partnumber, and cost.
float cost;
public:
void setpart (int mn, int pn, float c)
{ It has member function,
modelnumber = mn; setpart(), that supplies
partnumber = pn; values to all three data
cost = c; items at once.
}
void showpart()
{ It has another function,
cout << "Model " << modelnumber; showpart(), that displays
cout << ", part " << partnumber; the values stored in all three
items.
cout << ", costs " << cost << " pesos.\n";
}
};
main()
{ In this example only one object of type
part part1; part is created: part1.
#include <iostream>
using namespace std;
class length
{
private: In this program, the class
int feet; length contains two data
items, feet and inches.
float inches;
public:
void setlength (int ft, float in) The member function
setlength() uses
{ arguments to set the
feet = ft; values for feet and
inches = in; inches.
}
void getlength()
{
cout << "\nEnter Feet: "; The member function
cin >> feet; getlength() gets values for
cout << "Enter Inches: "; feet and inches from the
cin >> inches; user at the keyboard.
}
The member function
void showlength() showlength() displays the
values for feet and inches.
{
cout << feet << " feet and " << inches << " inches.";
}
};
main()
{
length len1, len2;
len1.setlength(11, 6.25);
The output of this program is:
len2.getlength();
Enter Feet: 17
Enter Inches: 5.75
cout << "\nLength 1 = ";
Length 1 = 11 feet and 6.25 inches.
len1.showlength(); Length 2 = 17 feet and 5.75 inches.
cout << "\nLength 2 = ";
len2.showlength();
}
• Counters as Objects
#include <iostream>
using namespace std;
main()
{
counter c1, c2;
c1.init_count();
c2.init_count(); The output of this program is:
cout << "\nc1= " << c1.get_count();
cout << "\nc2= " << c2.get_count(); c1=0
c2=0
c1.inc_count(); c1=1
c2.inc_count(); c2=2
c2.inc_count();
cout << "\nc1= " << c1.get_count();
cout << "\nc2= " << c2.get_count();
}
#include <iostream>
using namespace std;
class counter
{ The member function counter() is a
private: constructor. It will initialize an object upon
int count; creation.
public:
Constructor functions should have exactly
counter()
the same name (counter in this example) as
{ count = 0; } the class of which they are members. This is
void inc_count() one way the compiler knows they are
{ count = count + 1; } constructors.
int get_count()
{ return count; }
};
#include <iostream>
using namespace std;
class counter
{
No return type is used for constructors.
private:
int count;
Since the constructor is called automatically
public: by the system, there is no program for it to
counter() return anything to.
{ count = 0; }
void inc_count() This is the second way the compiler knows
{ count = count + 1; } they are constructors.
int get_count()
{ return count; }
};
• One of the most common tasks a constructor carries out is initializing data
members. In the counter class the constructor must initialize the count member
to 0. This was done in the constructor’s function body:
counter()
{ count = 0; }
• However, this is not the preferred approach. Here is how to initialize a data
member:
counter() : count(0)
{}
• The initialization takes place following the member function declarator but
before the function body. It is preceded by a colon. The value is placed in
parentheses following the member data.
#include <iostream>
using namespace std;
class counter
{
private:
int count;
public:
counter() : count(0)
{ }
void inc_count()
{ count = count + 1; }
int get_count()
{ return count; }
};
#include <iostream>
using namespace std;
main ()
class counter {
{ counter c1, c2;
private: };
int count;
public:
counter() : count(0)
{ cout << "\n Executing Constructor!";} The output of this program is:
void inc_count()
{ count = count + 1; } Executing Constructor!
int get_count() Executing Constructor!
{ return count; }
};
someclass()
{
m1 = 7;
m2 = 33;
m3 = 4;
}
They can be initialized by using the initializer list (also called the
member-initialization list):
#include <iostream>
using namespace std;
class length
{
private:
int feet;
float inches;
public:
void displaydata()
{
cout<< "\nFeet = "<< feet;
cout<< "\nInches = "<< inches;
}
};
main()
{
length len1, len2, len3; The output of this program is:
cout << "\n\nThe data for len3:"; The data for len3:
len3.displaydata(); Feet = 1
Inches = 0
}
#include <iostream>
using namespace std;
class area The member function area() is a
{ constructor.
private: It will initialize the length and
int length; breadth data members of an object
upon creation (length = 5 and
int breadth; breadth = 2).
public:
area(): length(5), breadth(2)
{}
void getdata()
{
cout << "Enter Length: ";
cin >> length;
cout << "Enter Breadth: ";
cin >> breadth;
}
int areacalculation()
{ return (length*breadth); }
cout << "\n\nDefault area when value is not taken from user:\n";
temp=a2.areacalculation();
a2.displayarea(temp);
}
#include <iostream>
using namespace std;
class area
{
private:
int length;
int breadth;
public:
area(int l, int b) This constructor sets the member
{ data length and breadth to
length = l; whatever values are passed as
breadth = b; arguments to the constructor upon
creation of the objects.
}
#include <iostream>
using namespace std;
class area
{
private:
int length;
int breadth;
public:
area(int l, int b): length(l), breadth(b)
{ }
void getdata()
{
cout << "Enter Length: ";
cin >> length;
cout << "Enter Breadth: ";
cin >> breadth;
}
void displaydata()
{
cout<< "\nLength = "<< length;
cout<< "\nBreath = "<< breadth;
}
};
main()
{
area a1(5, 2), a2 (10, -2), a3 (-5, 8); The output of this program is:
cout << "\n\nThe data for a3:"; The data for a3:
a3.displaydata(); Length = -5
Breadth = 8
}
#include <iostream>
using namespace std;
class area
{
private:
int length;
int breadth;
main()
{
area a1(5, 2), a2 (10, -2), a3 (-5, 8); The output of this program is:
cout << "\n\nThe data for a3:"; The data for a3:
a3.displaydata(); Length = 0
Breadth = 8
}
#include <iostream>
using namespace std;
class length
{
private:
int feet;
float inches;
public:
length () : feet (0), inches (0.0) Take note that there are three
{} member functions whose name
is length which is the same as
the name of the class.
length (int ft) : feet (ft)
{ inches = 0; }
This means that all three of
them are constructors.
length (int ft, float in) : feet (ft), inches (in)
{}
public:
public:
The member function length() is
a constructor with no
arguments. It will initialize the
length () : feet (0), inches (0.0) feet and inches data members of
{} an object upon creation (feet = 0
and inches = 0.0).
public:
public:
length (int ft, float in) : feet (ft), inches (in) It will accept two arguments
upon object creation and use
{} them in initializing the feet and
inches data members (feet = ft
and inches = in).
#include <iostream>
using namespace std;
class length
{
private:
int feet;
float inches;
public:
void displaydata()
{
cout<< "\nFeet = "<< feet;
cout<< "\nInches = "<< inches;
}
};
main()
{ The output of this program is:
length len1, len2(13);
length len3 (11, 6.25); The data for len1:
Feet = 0
cout << "\n\nThe data for len1:"; Inches = 0
len1.displaydata();
The data for len2:
cout << "\n\nThe data for len2:"; Feet = 13
len2.displaydata(); Inches = 0
cout << "\n\nThe data for len3:"; The data for len3:
len3.displaydata(); Feet = 11
} Inches = 6.25
#include <iostream>
using namespace std;
class length
{
private:
int feet;
float inches;
public:
length () : feet (0), inches (0.0)
{}
length (int ft, float in) : feet(ft), inches(in)
{}
void getlength()
{
cout << "\nEnter Feet: ";
cin >> feet;
cout << "Enter Inches: ";
cin >> inches;
}
void showlength()
{
cout << feet << " feet and " << inches << " inches.";
}
};
• The object len1 was initialize to the value of 11 feet and 6.25 inches using the
two-argument constructor:
• Then two more objects were define of type length, len2 and len3, initializing
both to the value of len1. These definitions both use the default copy
constructor.
This causes the default copy constructor for the length class to perform a
member-by-member copy of len1 into len2.
Model this tollbooth with a class called tollbooth. The two data items are a type int
to hold the total number of cars, and a type float to hold the total amount of money
collected. A constructor initializes both of these to 0. A member function called
payingcar() increments the car total and adds 150 pesos to the cash total. Another
function, called nonpayingcar(), increments the car total but adds nothing to the
cash total. Finally, a member function called display() displays the two totals.
In main(), the program should allow the user to enter 1 to count a paying car,
and 2 to count a nonpaying car. Entering 3 should cause the program to print out
the total cars and total cash and then exit. Entering any other input would cause
an error message to be displayed and program execution terminates.
The output of the program should follow the sample program run below:
Enter Choice: 1
Enter Choice: 2
Enter Choice: 1
Enter Choice: 1
Enter Choice: 2
Enter Choice: 1
Enter Choice: 3
2. An hourly employee is paid his hourly rate for up to 40 hours worked per week. Any hours over
that are paid at the overtime rate of 1.5 times that. From the worker’s gross or total pay, 1.5%
is withheld or deducted for social security tax, 3% is withheld for home development fund
(HDF) contribution, and 10% is withheld for professional income tax. If the worker has three or
more covered dependents, an additional 300 pesos is withheld to cover the extra cost of health
insurance beyond that paid by the employer. Write a C++ program that takes as input the
number of hours worked in a week and the number of dependents and then outputs the
workers gross pay, each withholding, and the net take home pay for the week.
Model this employee with a class called employee. It should have four data members
representing the ID number of the employee (of type int), the hourly rate (of type float), the
number of hours worked in a week (of type float), and the number of dependents (of type int).
It should have member functions for the following:
In main(), create two objects of class employee. Prompt the user the enter the data for each
object and compute and display the necessary information. The output of the program should
follow the sample program run below:
In main(), create two objects of class times. The parameters for the declaration of the first
object should be 17, 59, and 31 for hours, minutes, and seconds respectively. The parameters
for the declaration of the second object should be 1, 1, and 1 for hours, minutes, and seconds
respectively. Then prompt the user the enter the data for the second object. Display the
original data for the first object and then convert it to the 24-hour format and then display the
results. Do the same for the second object. The output of the program should follow the
sample program run below: