You are on page 1of 75

OBJECTS AND

CLASSES

SCHOOL OF COMPUTING MITCH M. ANDAYA


INTRODUCTION

• Placing data and functions together into a single entity is a


central idea in object-oriented programming.
Class
Data

data 1
data 2
data 3

Functions

func 1 ()
func 2 ()
func 3 ()

Objects and Classes


INTRODUCTION

• 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"; }
};

Objects and Classes


INTRODUCTION

#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.
};

Objects and Classes


INTRODUCTION

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();
}

Objects and Classes


DEFINING THE CLASS

• 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"; }
};

Objects and Classes


DEFINING THE CLASS

class simpleclass • The definition starts with the


keyword class, followed by the
{ class name—simpleclass in this
private: example.
int somedata;
• Like a structure, the body of the
public: class is delimited by braces and
terminated by a semicolon.
void setdata (int d)
{ somedata = d; } • A class definition requires a
semicolon at the end.
Remember, data constructs
void showdata() such as structures and classes
{ cout << "Data is " << somedata << "\n"; } end with a semicolon, while
}; control constructs such as
functions and loops do not.

Objects and Classes


DEFINING THE CLASS

• A key feature of object-oriented


class simpleclass programming is data hiding.
{ This means that data is
private: concealed within a class so that
it cannot be accessed
int somedata; mistakenly by functions outside
the class.
public:
• The primary mechanism for
void setdata (int d) hiding data is to put it in a class
{ somedata = d; } and make it private. Private
data or functions can only be
accessed from within the class.
void showdata()
{ cout << "Data is " << somedata << "\n"; } • Public data or functions, on the
}; other hand, are accessible from
outside the class.

Objects and Classes


DEFINING THE CLASS

• Usually the data within a


class is private and the
class simpleclass functions are public.
{
private:
int somedata; • This is a result of the way
classes are used.
public:
• The data is hidden so it
void setdata (int d) will be safe from
{ somedata = d; } accidental manipulation,
while the functions that
void showdata() operate on the data are
{ cout << "Data is " << somedata << "\n"; } public so they can be
}; accessed from outside the
class like in main() or
other classes.

Objects and Classes


DEFINING THE CLASS

class simpleclass • Class Data


{
private: The simpleclass class contains
int somedata; one data item: somedata,
which is of type int.
public:
The data items within a class
void setdata (int d) are called data members (or
sometimes member data).
{ somedata = d; }
There can be any number of
void showdata() data members in a class, just
{ cout << "Data is " << somedata << "\n"; } as there can be any number of
}; data items in a structure.

Objects and Classes


DEFINING THE CLASS

class simpleclass • Member Functions


{
private: Member functions (or
int somedata; methods) are functions that
are included within a class.
public: There are two member
functions in simpleclass:
void setdata (int d) setdata() and showdata().
{ somedata = d; }
Because setdata() and
void showdata() showdata() follow the
{ cout << "Data is " << somedata << "\n"; } keyword public, they can be
accessed from outside the
}; class.

Objects and Classes


DEFINING THE CLASS

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.
};

Objects and Classes


USING THE CLASS

• 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();
}

Objects and Classes


USING THE CLASS

main() • Defining Objects


{ The first statement in main() defines
simpleclass s1, s2; two objects, s1 and s2, of class
simpleclass.

Remember that the definition of the


s1.setdata(1066); class simpleclass does not create any
objects. It only describes how they will
s2.setdata(1776); look when they are created.

The objects are the ones that


s1.showdata(); participate in program operations.
s2.showdata(); Defining an object is similar to defining
a variable of any data type.
}

Objects and Classes


USING THE CLASS

Defining objects in this way


main() means creating them.
{
simpleclass s1, s2; This is also called instantiating
them.

s1.setdata(1066); The term instantiating arises


because an instance of the class
s2.setdata(1776); is created.

An object is an instance (that is,


s1.showdata(); a specific example) of a class.
s2.showdata();
} Objects are sometimes called
instance variables.

Objects and Classes


USING THE CLASS

• 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 ()

Objects and Classes


USING THE CLASS

main() • Calling Member Functions


{ The next two statements in main() call
simpleclass s1, s2; the member function setdata().

These statements do not look like


normal function calls.
s1.setdata(1066);
s2.setdata(1776); This syntax is used to call a member
function that is associated with a
specific object.
s1.showdata(); Because setdata() is a member
function of the simpleclass class, it
s2.showdata(); must always be called in connection
with an object of this class.
}

Objects and Classes


USING THE CLASS

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(); The dot operator is also


called the class member
s2.showdata(); access operator.
}

Objects and Classes


USING THE CLASS

main() The first call to setdata()


{
s1.setdata(1066);
simpleclass s1, s2;
executes the setdata() member
function of the s1 object. This function
s1.setdata(1066); sets the variable somedata in object s1
to the value 1066.
s2.setdata(1776);
The second call

s1.showdata(); s2.setdata(1776);

s2.showdata(); causes the variable somedata in s2 to


be set to 1776.
}

Objects and Classes


USING THE CLASS

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();
}

Objects and Classes


FUNCTIONS ARE PUBLIC, DATA IS PRIVATE

• 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.

Objects and Classes


FUNCTIONS ARE PUBLIC, DATA IS PRIVATE

• Similarly, if the member function showdata() was


defined as private, then the statement

s1.showdata();

in main() would have resulted in an error.

• However, there is no rule that says data must be


private and functions public; there will be
circumstances wherein there is a need to use
private functions and public data.

Objects and Classes


MORE EXAMPLES

• Machine Parts as Objects

#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.
}

Objects and Classes


MORE EXAMPLES

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.

part1.setpart (6244, 373, 217.55); The output of the program:


part1.showpart();
} Model 6244, part 373, costs 217.55 pesos.

Objects and Classes


MORE EXAMPLES

• Measurements as Objects (Length)

#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.
}

Objects and Classes


MORE EXAMPLES

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.";
}
};

Objects and Classes


MORE EXAMPLES

main() In this example two objects of


{ type length are created: len1
length len1, len2; and len2.

Object len1 gets the values for


len1.setlength(11, 6.25); its feet and inches from the
len2.getlength(); arguments passed to it through
the setlength() member
function. For len1, feet = 11
cout << "\nLength 1 = "; and inches = 6.25.
len1.showlength();
cout << "\nLength 2 = "; Object len2 gets the values for
its feet and inches from the
len2.showlength(); user through the getlength()
} member function.

Objects and Classes


MORE EXAMPLES

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();
}

Objects and Classes


MORE EXAMPLES

• Counters as Objects

#include <iostream>
using namespace std;

class counter The counter class has one data member


{ which is count of type int.
private:
int count;
It has three member functions:
public:
void init_count() init_count() which initializes count to 0
{ count = 0; }
void inc_count() inc_count() which adds 1 to count
{ count = count + 1; }
int get_count()
{ return count; } get_count() which returns the current
};
value of count.

Objects and Classes


MORE EXAMPLES

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();
}

Objects and Classes


CONSTRUCTORS

• Sometimes it is convenient if an object can


initialize itself upon creation, without requiring a
separate call to a member function (as in the
counter example).

• Automatic initialization is carried out using a


special member function called a constructor.

• A constructor is a member function that is


executed automatically whenever an object is
created.

Objects and Classes


CONSTRUCTORS

• Revised Counter Program (using constructors)

#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; }
};

Objects and Classes


CONSTRUCTORS

• Revised Counter Program (using constructors)

#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; }
};

Objects and Classes


CONSTRUCTORS

• 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.

Objects and Classes


CONSTRUCTORS

• Revised Counter Program (using constructors)

#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; }
};

Objects and Classes


CONSTRUCTORS

• To show the execution of constructors:

#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; }
};

Objects and Classes


CONSTRUCTORS

• In initializing multiple members, instead of writing:

someclass()
{
m1 = 7;
m2 = 33;
m3 = 4;
}

They can be initialized by using the initializer list (also called the
member-initialization list):

someclass() : m1(7), m2(33), m2(4) ← initializer list


{}

Objects and Classes


CONSTRUCTORS

• The reasons for not initializing member data in the body of


the constructor have to do with the fact that members
initialized in the initializer list are given a value before the
constructor even starts to execute.

• This is important in some situations. For example, the


initializer list is the only way to initialize const member
data and references.

• Actions more complicated than simple initialization must


be carried out in the constructor body, as with ordinary
functions.

Objects and Classes


CONSTRUCTORS

• Notice that the previous examples worked without


constructors such as in the Measurements as Objects
(Length) Program. In main(), the objects declarations:

length len1, len2;

worked just fine.

• This is because an implicit no-argument constructor is built


into the program automatically by the compiler, and it’s
this constructor that created the objects, even though it
wasn’t defined in the class.

Objects and Classes


CONSTRUCTORS

• This no-argument constructor is called the default


constructor. If it were not created automatically by
the constructor, the program would not be able to
create objects of a class for which no constructor
was defined.

• Often programmers would want to initialize data


members in the default (no-argument) constructor
as well. If the default constructor would do it, then
the values the data members may be given will not
be known.

Objects and Classes


CONSTRUCTORS

• Example for Default Constructor:

#include <iostream>
using namespace std;

class length
{
private:
int feet;
float inches;

public:
void displaydata()
{
cout<< "\nFeet = "<< feet;
cout<< "\nInches = "<< inches;
}
};

Objects and Classes


CONSTRUCTORS

main()
{
length len1, len2, len3; The output of this program is:

The data for len1:


cout << "\n\nThe data for len1:"; Feet = 1995969920
len1.displaydata(); Inches = 0

The data for len2:


cout << "\n\nThe data for len2:";
Feet = 3
len2.displaydata(); Inches = 0

cout << "\n\nThe data for len3:"; The data for len3:
len3.displaydata(); Feet = 1
Inches = 0
}

Objects and Classes


CONSTRUCTORS

• Example: Area Program (using constructors)

#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)
{}

Objects and Classes


CONSTRUCTORS

void getdata()
{
cout << "Enter Length: ";
cin >> length;
cout << "Enter Breadth: ";
cin >> breadth;
}

int areacalculation()
{ return (length*breadth); }

void displayarea(int temp)


{
cout<< "Area = "<< temp;
}
};

Objects and Classes


CONSTRUCTORS

main() The output of this program is:


{
Enter Length: 20
area a1, a2; Enter Breadth: 8
int temp; Area = 160

a1.getdata(); Default area when value is not taken from user:


temp=a1.areacalculation(); Area = 10
a1.displayarea(temp);

cout << "\n\nDefault area when value is not taken from user:\n";

temp=a2.areacalculation();
a2.displayarea(temp);
}

Objects and Classes


CONSTRUCTORS WITH ARGUMENTS

• Revised Area Program (using constructors with arguments)

#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.
}

Objects and Classes


CONSTRUCTORS WITH ARGUMENTS

• Revised Area Program (using constructors with arguments – better


approach)

#include <iostream>
using namespace std;
class area
{
private:
int length;
int breadth;
public:
area(int l, int b): length(l), breadth(b)
{ }

Objects and Classes


CONSTRUCTORS WITH ARGUMENTS

void getdata()
{
cout << "Enter Length: ";
cin >> length;
cout << "Enter Breadth: ";
cin >> breadth;
}

void displaydata()
{
cout<< "\nLength = "<< length;
cout<< "\nBreath = "<< breadth;
}
};

Objects and Classes


CONSTRUCTORS WITH ARGUMENTS

main()
{
area a1(5, 2), a2 (10, -2), a3 (-5, 8); The output of this program is:

The data for a1:


cout << "\n\nThe data for a1:"; Length = 5
a1.displaydata(); Breadth = 2

The data for a2:


cout << "\n\nThe data for a2:";
Length = 10
a2.displaydata(); Breadth = -2

cout << "\n\nThe data for a3:"; The data for a3:
a3.displaydata(); Length = -5
Breadth = 8
}

Objects and Classes


CONSTRUCTORS WITH COMPLICATED INITIALIZATIONS

• As mentioned earlier, actions more complicated than


simple initialization must be carried out in the constructor
body, as with ordinary functions. For example:

#include <iostream>
using namespace std;
class area
{
private:
int length;
int breadth;

Objects and Classes


CONSTRUCTORS WITH COMPLICATED INITIALIZATIONS

In this example, if the argument


public: that was passed for length
area(int l, int b): length(l), breadth(b) (which is l) is a negative number,
the constructor will assign 0 to
{ the data member length.
if (l < 0)
length = 0; Similarly, if the argument that
if (b < 0) was passed for breadth (which is
breadth = 0; b) is also a negative number, the
} constructor will assign 0 to the
data member breadth.
void displaydata()
{
cout<< "\nLength = "<< length;
cout<< "\nBreath = "<< breadth;
}
};

Objects and Classes


CONSTRUCTORS WITH COMPLICATED INITIALIZATIONS

main()
{
area a1(5, 2), a2 (10, -2), a3 (-5, 8); The output of this program is:

The data for a1:


cout << "\n\nThe data for a1:"; Length = 5
a1.displaydata(); Breadth = 2

The data for a2:


cout << "\n\nThe data for a2:";
Length = 10
a2.displaydata(); Breadth = 0

cout << "\n\nThe data for a3:"; The data for a3:
a3.displaydata(); Length = 0
Breadth = 8
}

Objects and Classes


OVERLOADED CONSTRUCTORS

• A constructor can be overloaded with different versions taking


different parameters: with a different number of parameters
and/or parameters of different types. The compiler will
automatically call the one whose parameters match the
arguments. For example:

#include <iostream>
using namespace std;

class length
{
private:
int feet;
float inches;

Objects and Classes


OVERLOADED CONSTRUCTORS

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)
{}

Objects and Classes


OVERLOADED CONSTRUCTORS

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)


{}

Objects and Classes


OVERLOADED CONSTRUCTORS

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).

length (int ft) : feet (ft)


{ inches = 0; }

length (int ft, float in) : feet (ft), inches (in)


{}

Objects and Classes


OVERLOADED CONSTRUCTORS

public:

length () : feet (0), inches (0.0) The member function length(int


{} ft) is also a constructor but with
one arguments.

It will accept an argument upon


length (int ft) : feet (ft) object creation and use it in
{ inches = 0.0; } initializing feet (feet = ft).

It will then initialize inches to 0.0


length (int ft, float in) : feet (ft), inches (in) (inches = 0.0).
{}

Objects and Classes


OVERLOADED CONSTRUCTORS

public:

length () : feet (0), inches (0.0)


{}

length (int ft) : feet (ft) The member function length(int


{ inches = 0; } ft, float in) is also a constructor
but with two arguments.

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).

Objects and Classes


OVERLOADED CONSTRUCTORS

• Since there are now more than one explicit constructors


with the same name, length(), then it can be said that the
constructor is overloaded.

• Which of the three constructors is executed when an object


is created depends on how many arguments are used in
the definition:

length len1; calls the first constructor

length len2 (13); calls the second constructor

length len3 (11, 6.25); calls the third constructor

Objects and Classes


OVERLOADED CONSTRUCTORS

• Revised Length Program (with overloaded constructors)

#include <iostream>
using namespace std;

class length
{
private:
int feet;
float inches;

Objects and Classes


OVERLOADED CONSTRUCTORS

public:

length () : feet (0), inches (0.0)


{}
length (int ft) : feet (ft)
{ inches = 0; }
length (int ft, float in) : feet (ft), inches (in)
{}

void displaydata()
{
cout<< "\nFeet = "<< feet;
cout<< "\nInches = "<< inches;
}
};

Objects and Classes


OVERLOADED CONSTRUCTORS

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

Objects and Classes


THE DEFAULT COPY CONSTRUCTOR

• So far, there are two ways to initialize objects:

– A no-argument constructor can initialize data members to


constant values, and
– a multi-argument constructor can initialize data members to
values passed as arguments.

• Another way to initialize an object is to initialize it with another


object of the same type.

• There is no need to create a special constructor for this; one is


already built into all classes. It’s called the default copy
constructor. It is a one-argument constructor whose argument is
an object of the same class as the constructor.

Objects and Classes


THE DEFAULT COPY CONSTRUCTOR

• Revised Length Program (using default copy constructors)

#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)
{}

Objects and Classes


THE DEFAULT COPY CONSTRUCTOR

void getlength()
{
cout << "\nEnter Feet: ";
cin >> feet;
cout << "Enter Inches: ";
cin >> inches;
}

void showlength()
{
cout << feet << " feet and " << inches << " inches.";
}
};

Objects and Classes


THE DEFAULT COPY CONSTRUCTOR

main() The output of this program is:

{ Length 1 = 11 feet and 6.25 inches.


length len1 (11, 6.25); Length 2 = 11 feet and 6.25 inches.
Length 3 = 11 feet and 6.25 inches.
length len2 (len1);
length len3 = len1;

cout << "\nLength 1 = "; len1.showlength();


cout << "\nLength 2 = "; len2.showlength();
cout << "\nLength 3 = "; len3.showlength();
}

Objects and Classes


THE DEFAULT COPY CONSTRUCTOR

• The object len1 was initialize to the value of 11 feet and 6.25 inches using the
two-argument constructor:

length len1 (11, 6.25);

• 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.

• The object len2 is initialized in the statement:

length len2 (len1);

This causes the default copy constructor for the length class to perform a
member-by-member copy of len1 into len2.

Objects and Classes


THE DEFAULT COPY CONSTRUCTOR

• A different format has exactly the same


effect, causing len1 to be copied member-
by-member into len3:

length len3 = len1;

Although this looks like an assignment


statement, it is not. Both formats invoke the
default copy constructor, and can be used
interchangeably.
Objects and Classes
MACHINE PROBLEMS

1. Assume there is a tollbooth at a highway. Cars passing by the booth are


expected to pay a 150-peso toll. Mostly they do, but sometimes a car goes by
without paying. The tollbooth keeps track of the number of cars that have gone
by, and of the total amount of money collected.

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.

Objects and Classes


MACHINE PROBLEMS

The output of the program should follow the sample program run below:

Enter 1 for Each Non-paying Car


Enter 2 for Each Paying Car
Enter 3 to Display Results and Exit the Program

Enter Choice: 1
Enter Choice: 2
Enter Choice: 1
Enter Choice: 1
Enter Choice: 2
Enter Choice: 1
Enter Choice: 3

Total Number of Cars = 6


Total Cash Collected = 300 pesos
Program Exiting!

Objects and Classes


MACHINE PROBLEMS

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:

a) A constructor that initializes all data members to 0.


b) Prompt the user to enter the values for the four data members.
c) Calculate and return the gross pay of the employee.
d) Calculate and print the social security tax, the HDF contribution, the professional income
tax, the health insurance, and the net pay of the employee.

Objects and Classes


MACHINE PROBLEMS

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:

For Data for 1st Employee:


Enter the ID number: 12345
Enter the hourly rate: 500
Enter the number of hours worked this week: 45
Enter the number of dependents: 4

For Employee 12345:

Gross Pay = 23750 pesos

Social Security Tax = 356.25 pesos


HDF = 712.5 pesos
Professional Income Tax = 2375 pesos
Health Insurance = 300 pesos

Net Take Home Pay for the Week = 20006.2 pesos

Objects and Classes


MACHINE PROBLEMS

For Data for 2nd Employee:


Enter the ID number: 67890
Enter the hourly rate: 350
Enter the number of hours worked this week: 39
Enter the number of dependents: 2

For Employee 67890:

Gross Pay = 13650 pesos

Social Security Tax = 204.75 pesos


HDF = 409.5 pesos
Professional Income Tax = 1365 pesos
Health Insurance = 0 pesos

Net Take Home Pay for the Week = 11670.8 pesos

Objects and Classes


MACHINE PROBLEMS

3. Create a class called times that has separate int data


members for hours, minutes, and seconds representing
time in the 24-hour format. It should have member
functions for the following:

a) A constructor that initializes all data members to fixed


values upon declaration.
b) Prompt the user to enter the values for the three data
members.
c) Display the values of the data members.
d) Converts and display the time in the 12-hour format
(without the seconds).

Objects and Classes


MACHINE PROBLEMS

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:

Enter Hours, Minutes, and Seconds for the 2nd Time:


Hours: 24
Minutes: 43
Seconds: 29

The first time is 17 hours, 59 minutes, and 31 seconds.


The time is 6:00 p.m.

The second time is 24 hours, 43 minutes, and 29 seconds.


The time is 12:43 am.

Objects and Classes

You might also like