Ch 7-1. Object-Oriented
Programming and Classes
2014-1 Programming Language
May 10, 2014
Prof. Young-Tak Kim
Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School,
Yeungnam University, KOREA
(Tel : +82-53-810-2497; Fax : +82-53-810-4742
Outline
Classes
z Object-Oriented Programming Concept
z Defining, member functions
z Public and private members
z Accessor and mutator functions
z Structures vs. classes
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 3 Programming LanguageProf. Young-Tak Kim
Major Considerations in
Large-scale Software System Developments
Procedure of Design, Development and Maintenance
of Large-Scale Software
z Requirements analysis
z Software design
z Unit testing
z Component testing
z System testing
z Maintenance
Major Considerations
z Clear unit/component/sub-system interface
z Stability of unit/component/sub-system
z Easy modification/update of unit/component/sub-system without
great impact on other parts
Object-Oriented Programming (OOP)
Object-Oriented Programming Object-oriented
programming (
OOP
) (
객체 지향형 프로그래밍
)
z an approach to designing
modular
,
reusable
software systems
z a
programming paradigm
that represents the concept of "
objects
"
that have
data fields
(attributes that describe the object) and
associated procedures known as
methods
z Objects, which are usually
instances
of
classes
, are used to interact
with one another to design applications and computer programs
Goals of object-oriented programming :
z
Increased understanding: rather than talking about database
tables and programming subroutines, the developer talks about
things the user is familiar with: objects from their application domain
z
Ease of maintenance
and
adoption of new technologies by
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 5 Programming LanguageProf. Young-Tak Kim
Classes
Similar to structures
z Not only, just member data
z But also, adds member functions
Integral to object-oriented programming
z Focus on objects
Object: Contains data and operations
Class: mold (주형 형틀, 거푸집) to instantiate an object
In C++,
variables
of
class type
are
objects
Class Definitions
Defined similar to structures
Example:
class DayOfYear
// name of new class type
{
public:
// access specifier
void output();
// member function
int month;
// data member
int day;
// data member
};
Notice only member function’s prototype
z Function’s implementation is elsewhere
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 7 Programming LanguageProf. Young-Tak Kim
Declaring Objects
Declared same as all variables
z Predefined types, structure types
Example:
DayOfYear today, birthday
;
Declares two objects of class type DayOfYear
Objects include:
z Data (attribute)
Members: month, day
z Operations (member functions)
Class Member Access
Members accessed same as structures
Example:
today.month
today.day
z And to access member function:
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 9 Programming LanguageProf. Young-Tak Kim
Class Member Functions
Must define or "implement" class member
functions
Like other function definitions
z Can be after main() definition
z Must specify class:
void DayOfYear::output()
{
…
}
::
is
scope resolution operator
Instructs compiler "what class" member is from
Item before :: called type qualifier
Class Member Functions Definition
Notice output() member function’s
definition (in next example)
Refers to member data of class
z No qualifiers
Function used for all objects of the class
z Will refer to "that object’s" data when invoked
z Example:
today.output();
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 11 Programming LanguageProf. Young-Tak Kim
Complete Class Example:
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 13 Programming LanguageProf. Young-Tak Kim
Display 6.3 Class With a Member Function (3 of 4)
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 15 Programming LanguageProf. Young-Tak Kim
Dot
(.) operator and
Scope Resolution (::)
Operator
Used to specify "of what thing" they are
members
Dot operator (.) :
z Specifies member of particular object
Scope resolution operator (::)
z Specifies what class the function definition comes from
class DayOfYear {
public: // access specifier
void output(); // member function
int month; // data member
int day; // data member
}; DayOfYear::output() { } DayOfYear today; today.year = 2014; today.month = 5;
A Class’s Place
Class is full-fledged type!
z Just like data types int, double, etc.
Can have variables of a class type
z We simply call them "objects"
Can have parameters of a class type
z Pass-by-value
z Pass-by-reference
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 17 Programming LanguageProf. Young-Tak Kim
Encapsulation
Any data type includes
z Data (range of data)
z Operations (that can be performed on data)
Example:
int
data type has:
Data: +-32,767
Operations: +,-,*,/,%, logical, etc.
Same with classes
z But WE specify data, and the operations to
be allowed on our data!
Abstract Data Type (ADT)
"Abstract"
z Programmers don’t know details
Abbreviated "ADT"
z Collection of data values together with set
of basic operations defined for the values
ADT’s often "language-independent"
z We implement ADT’s in C++ with classes
C++ class "defines" the ADT
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 19 Programming LanguageProf. Young-Tak Kim
More on Encapsulation
Encapsulation
z Means "bringing together as one"
Declare a class Æ get an object
Object is "encapsulation" of
z Data values (attributes)
Principles of OOP
Encapsulation
z Bring together data and operations,
but keep "details" hidden
Information Hiding
z Details of its implementations and its operations work
not known to "user" of class
Data Abstraction
z Details of how data is manipulated within
ADT/class not known to user
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 21 Programming LanguageProf. Young-Tak Kim
Encapsulation in Object
Encapsulation and protection of private data
ObjectPrivateData Members Private Member Functions - house keeping
Public Member Functions
- get() // read with validity check - set() // write with validity check Friend Functions
- cin >> // standard input - cout << // standard output
interface to outside
outside
program
Public and Private Members
Data in class almost always designated
private in definition!
z Upholds principles of OOP
z Hide data from user
z Allow manipulation only via operations
Which are member functions
Public items (usually member functions)
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 23 Programming LanguageProf. Young-Tak Kim
Public and Private Example
Modify previous example:
class DayOfYear
{
public:
void input();
void output();
private:
int month;
int day;
};
Data now private
Public and Private Example 2
Given previous example
Declare object:
DayOfYear today;
Object
today
can ONLY access
public members
z cin >> today.month;
// NOT ALLOWED!
z cout << today.day;
// NOT ALLOWED!
z Must instead call public operations:
today.input();
today.output();
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 25 Programming LanguageProf. Young-Tak Kim
Public and Private Style
Typically place public first
z Allows easy viewing of portions that can be
USED by programmers using the class
z Private data is "hidden", so irrelevant to users
Can mix and match public and private
Outside of class definition,
cannot change (or even access) private
data
Accessor and Mutator Functions
Object needs to "do something" with its
data
Accessor
member functions
z Allow object to read data
z Also called "get member functions"
z Simple retrieval of member data
Mutator
member functions
z Allow object to change data
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 27 Programming LanguageProf. Young-Tak Kim
// Display 6.4 Class with Private Members
#include <iostream> #include <cstdlib> using namespace std; class DayOfYear { public: void input( ); void output( );
void set(int newMonth, int newDay);
//Precondition: newMonth and newDay form a possible date. void set(int newMonth);
//Precondition: 1 <= newMonth <= 12
//Postcondition: The date is set to the first day of the given month. int getMonthNumber( ); //Returns 1 for January, 2 for February, etc. int getDay( );
private:
int month; int day;
int main( )
{
DayOfYear today, bachBirthday; cout << "Enter today's date:₩n"; today.input( );
cout << "Today's date is "; today.output( );
cout << endl;
bachBirthday.set(3, 21);
cout << "J. S. Bach's birthday is "; bachBirthday.output( );
cout << endl;
if ( today.getMonthNumber( ) == bachBirthday.getMonthNumber( ) && today.getDay( ) == bachBirthday.getDay( ) )
cout << "Happy Birthday Johann Sebastian!₩n"; else
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 29 Programming LanguageProf. Young-Tak Kim //Uses iostream and cstdlib:
void DayOfYear::set(int newMonth, int newDay)
{
if ((newMonth >= 1) && (newMonth <= 12)) month = newMonth;
else {
cout << "Illegal month value! Program aborted.₩n"; exit(1);
}
if ((newDay >= 1) && (newDay <= 31)) day = newDay;
else {
cout << "Illegal day value! Program aborted.₩n"; exit(1);
} }
//Uses iostream and cstdlib:
void DayOfYear::set(int newMonth)
{
if ((newMonth >= 1) && (newMonth <= 12)) month = newMonth;
else {
cout << "Illegal month value! Program aborted.₩n"; exit(1);
}
day = 1; }
int DayOfYear::getMonthNumber( ) { return month; } int DayOfYear::getDay( ) { return day; }
//Uses iostream and cstdlib: void DayOfYear::input( ) {
cout << "Enter the month as a number: "; cin >> month;
cout << "Enter the day of the month: "; cin >> day;
if ((month < 1) || (month > 12) || (day < 1) || (day > 31)) {
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 31 Programming LanguageProf. Young-Tak Kim
void DayOfYear::output( )
{
switch (month) {
case 1: cout << "January "; break; case 2: cout << "February "; break; case 3: cout << "March "; break; case 4: cout << "April "; break; case 5: cout << "May "; break; case 6: cout << "June "; break; case 7: cout << "July "; break; case 8: cout << "August "; break; case 9: cout << "September "; break; case 10: cout << "October "; break; case 11: cout << "November "; break; case 12: cout << "December "; break; default:
cout << "Error in DayOfYear::output. Contact software vendor."; } // end switch
cout << day; }
Separation of
Interface
and
Implementation
User of class need not see details of how
class is implemented
z Principle of OOP Æ encapsulation
User only needs "rules"
z Called "
interface
" for the class
In C++ Æ public member functions and
associated comments
Implementation
of class is
hidden
z Member function definitions elsewhere
z User need not see them
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 33 Programming LanguageProf. Young-Tak Kim
Structures vs. Classes
Structures
z Typically all members public
z No member functions
Classes
z Typically all data members private
z Interface member functions public
Technically, same
Thinking Objects
Focus for programming changes
z Before Æ algorithms center stage
z Object-Oriented Programming (OOP) Æ data is focus
Algorithms still exist
z They simply focus on their data
z Are "made" to "fit" the data
Designing software solution
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 35 Programming LanguageProf. Young-Tak Kim
Summary 7-1-1
Structure
is collection of different types
Class
used to combine data and functions
into single unit ->
object
Member variables and member functions
z Can be public Æ accessed outside class
z Can be private Æ accessed only in a member
function’s definition
Class and structure types can be formal
Summary 7-1-2
C++ class definition
z Should separate two key parts
Interface: what user needs
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 37 Programming LanguageProf. Young-Tak Kim
Homework 7-1
7-1.1 Structure of planets in the solar system.
Each planet has following information:
Name : a character string of less than 10 characters
Relative-Mass : double type value of mass relative to Earth
Distance from sun : double type value of mean distance from sun in [10
6Km]
1) Design a structure for a planet with the information of planets.
struct Planet
{
char name[10];
double relativeMass;
double distance;
};
2) Using the structure designed above, make an array Planet
solar_planet[9], and initialize the array from an input file
“solar_planet.dat” which contains following data :
Name of Planet Relative Mass Distance from Sun
Mercury 0.0558 57.9 Venus 0.815 108 Earth 1.0 150 Mars 0.107 228 Jupiter 318 778 Saturn 95.1 1430 Uranus 14.5 2870 Neptune 17.2 4500 Pluto 0.11 5900
3) Using the solar_planet[ ] array, make a sorted list of solar planets in
non-decreasing order of relative mass. Output the result to
“sortedSolarPlanet.dat” in the same format of input file.
4) Using the solar_planet[ ] array, make a sorted list of solar planets in
non-decreasing order of distance from Sun. Output the result to
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 39 Programming LanguageProf. Young-Tak Kim
7-1.2 Write a header file “
Class_Planet.h
” with a “
class Planet
” with
following members:
(1) Private Data members:
. name: a character string of less than 10 characters
. relativeMass: double type value of mass relative to Earth
. distance: double type value of mean distance from sun in [106 Km]
(2) Public methods:
. constructor: constructs the object instance of Planet with given arguments . destructor: destructs the object instance of Planet
. print(): printout the name, relative mass and distance of the planet object . setName(): set name that truncate the name if the length is longer than 10
characters
. setRelMass(): set relative mass when the passed value is greater than 0 and less than 100; otherwise the value is set to 0
. setDist(): set distance when the passed value is greater than 0 and less than 10,000.
. getName(): returns the name of the planet . getRelMass(): returns the relative distance . getDistance(): returns the distance
7-1.3 Write a header file “
SolarSystem
.h” that includes
“
Class_Planet
.h” and contains a “
class SolarSystem
” with
following members:
(1) Private Data members:
. planets: array of planet object instances
(2) Public methods:
. constructor: constructs the object instance of SolarSystem
. destructor: destructs the object instance of SolarSystem
. addPlanet: create a new planet with given parameters for the planet
. deletePlanet: delete a planet with the given planet name
. sortPlanetsByName(): sort the planets in the solar system in the
non-decreasing order of name
. sortByRelMass(): sort the planets in the solar system in the
non-decreasing order of relative mass
. sortByDistance():sort the planets in the solar system in the
non-decreasing order of distance
Advanced Networking Tech. Lab.
Yeungnam University (YU-ANTL) ch 7-1 - 41 Programming LanguageProf. Young-Tak Kim
7-1.4 Write a “
solarSystem.cpp
” that includes the header file
“
Class_Planet.h
” and “
solarSystem.h
”.
(1) This program reads in “solarSystem.dat” file to create & initialize the
solar system.
(2) It prints out the sorted list of planets in the solar system:
i) in non-decreasing order of name,
ii) in non-decreasing order of relative mass,
iii) in non-decreasing order of distance.
(3) Contents of “solarSystem.dat” file
Name of Planet Relative Mass
Distance from Sun
Mercury
0.0558
57.9
Venus
0.815
108
Earth
1.0
150
Mars
0.107
228
Jupiter
318
778
Saturn
95.1
1430
Uranus
14.5
2870
Neptune
17.2
4500
Pluto
0.11
5900