Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP)
Introduction
Object-oriented programming (OOP)
Encapsulates data (attributes) and functions (behavior) into
packages called classes
Information hiding
Class objects communicate across well-defined interfaces
Implementation details hidden within classes themselves
int second;
};
Structure Definitions
Self-referential structure
Structure member cannot be instance of enclosing struct
Structure member can be pointer to instance of enclosing
struct (self-referential structure)
Used for linked lists, queues, stacks and trees
struct definition
Creates new data type used to declare variables
Structure variables declared like variables of other types
Examples:
Time timeObject;
Time timeArray[ 10 ];
Time *timePtr;
Time &timeRef = timeObject;
Accessing Structure Members
Member access operators
Dot operator (.) for structure and class members
C-style structures
No interface
If implementation changes, all programs using that struct must
change accordingly
Classes
Model objects
Attributes (data members)
Behaviors (member functions)
Defined using keyword class
Member functions
Methods
Invoked in response to messages
Constructor function
Special member function
Initializes data members
Same name as class
Several constructors
Function overloading
No return type
1 class Time {
2
3 public:
4 Time(); // constructor
5 void setTime( int, int, int ); // set hour, minute,
second
6 void printUniversal(); // print universal-
time format
7 void printStandard(); // print standard-
time format
8
9 private:
10 int hour; // 0 - 23 (24-hour clock format)
11 int minute; // 0 - 59
12 int second; // 0 - 59
13
14 }; // end class Time
Implementing a Time Abstract Data Type
with a class
Objects of class
After class definition
Class name new type specifier
C++ extensible language
Object, array, pointer and reference declarations
Example: Class name becomes new type
specifier.
22 private:
23 int hour; // 0 - 23 (24-hour clock format)
24 int minute; // 0 - 59
25 int second; // 0 - 59 Constructor initializes private
26 data members to 0.
27 }; // end class Time
29 // Time constructor initializes each data member to zero and
30 // ensures all Time objects start in a consistent state
31 Time::Time() {
33 hour = minute = second = 0;
34
35 } // end Time constructor
36
37 // set new Time value using universal time, perform validity
38 // checks on the data values and set invalid values to zero
39 void Time::setTime( int h, int m, int s )
40 {
41 hour = ( h >= 0 && h < 24 ) ? h : 0; public member function checks
42 minute = ( m >= 0 && m < 60 ) ? m : 0; parameter values for validity
43 second = ( s >= 0 && s < 60 ) ? s : 0; before setting private data
44 members.
45 } // end function setTime
No arguments (implicitly know
47 // print Time in universal format purpose is to print data members);
48 void Time::printUniversal() member function calls more concise.
49 {
50 cout << setfill( '0' ) << setw( 2 ) << hour << ":"
51 << setw( 2 ) << minute << ":"
52 << setw( 2 ) << second;
53
54 } // end function printUniversal
55
56 // print Time in standard format
57 void Time::printStandard()
58 {
59 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
60 << ":" << setfill( '0' ) << setw( 2 ) << minute
61 << ":" << setw( 2 ) << second
62 << ( hour < 12 ? " AM" : " PM" );
63
64 } // end function printStandard
65
66 int main()
67 {
68 Time t; // instantiate object t of class Time
69
Declare variable t to be object of
class Time.
Interfaces
Hide implementation
Software reuse
Composition (aggregation)
Class objects included as members of other classes
Inheritance
New classes derived from old
Class Scope and Accessing Class Members
Class scope
Data members, member functions
Within class scope
Class members
Immediately accessible by all member functions
Referenced by name
Outside class scope
Referenced through handles
Object name, reference to object, pointer to object
File scope
Nonmember functions
Function scope
Variables declared in member function
Only known to function
Variables with same name as class-scope variables
Class-scope variable hidden
Access with scope resolution operator (::)
ClassName::classVariableName
Header files
Class definitions and function prototypes
Included in each file using class
#include
File extension .h
Source-code files
Member function definitions
Same base name
Convention
Compiled and linked
Access modes
private
Default access mode
Accessible to member functions and friends
public
Accessible to any function in program with handle to
class object
protected
Will be discussed in later lectures
Access functions
public
Read/display data
Predicate functions
Check conditions
1 // salesp.cpp
2 // Member functions for class SalesPerson.
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8 using std::fixed;
9
10 #include <iomanip>
11
12 using std::setprecision;
13
14 // include SalesPerson class definition from salesp.h
15 #include "salesp.h"
16
17 // initialize elements of array sales to 0.0
18 SalesPerson::SalesPerson()
19 {
20 for ( int i = 0; i < 12; i++ )
21 sales[ i ] = 0.0;
22
23 } // end SalesPerson constructor
24
25 // get 12 sales figures from the user at the keyboard
26 void SalesPerson::getSalesFromUser() {
28 double salesFigure;
30 for ( int i = 1; i <= 12; i++ ) {
31 cout << "Enter sales amount for month " << i << ": ";
32 cin >> salesFigure;
33 setSales( i, salesFigure );
34
35 } // end for Set access function performs
36 validity checks.
37 } // end function getSalesFromUser
39 // set one of the 12 monthly sales figures; function
subtracts
40 // one from month value for proper subscript in sales array
41 void SalesPerson::setSales( int month, double amount )
42 {
43 // test for valid month and amount values
44 if ( month >= 1 && month <= 12 && amount > 0 )
45 sales[ month - 1 ] = amount; // adjust for subscripts
0-11
47 else // invalid month or amount value
48 cout << "Invalid month or sales figure" << endl;
Initializers
Passed as arguments to constructor
In parentheses to right of class name before semicolon
Class-type ObjectName( value1,value2,);
OR
1 // time2.cpp
2 // Member-function definitions for class Time.
3 #include <iostream>
4
5 using std::cout;
6
7 #include <iomanip>
8
9 using std::setfill;
10 using std::setw;
11
12 // include definition of class Time from time2.h
13 #include "time2.h"
14
15 // Time constructor initializes each data member to zero;
16 // ensures all Time objects start in a consistent state
17 Time::Time( int hr, int min, int sec )
18 {
19 setTime( hr, min, sec ); // validateConstructor
and set calls time
setTime to
validate passed (or default)
20
values.
21 } // end Time constructor
22
23 // set new Time value using universal time, perform validity
24 // checks on the data values and set invalid values to zero
25 void Time::setTime( int h, int m, int s )
26 {
27 hour = ( h >= 0 && h < 24 ) ? h : 0;
28 minute = ( m >= 0 && m < 60 ) ? m : 0;
29 second = ( s >= 0 && s < 60 ) ? s : 0;
30
31 } // end function setTime
32
33 // print Time in universal format
34 void Time::printUniversal()
35 {
36 cout << setfill( '0' ) << setw( 2 ) << hour << ":"
37 << setw( 2 ) << minute << ":"
38 << setw( 2 ) << second;
39
40 } // end function printUniversal
41
Destructors
Destructors
Special member function
Same name as class
Preceded with tilde (~)
No arguments
No return value
Cannot be overloaded
Performs termination housekeeping
Before system reclaims objects memory
Reuse memory for new objects
No explicit destructor
Compiler creates empty destructor
When Constructors/Destructors Are Called
+1 // create.h
2 // Definition of class CreateAndDestroy.
3 // Member functions defined in create.cpp.
4 #ifndef CREATE_H Constructor and destructor
5 #define CREATE_H member functions.
6
7 class CreateAndDestroy {
8
9 public:
private members to show order
10 CreateAndDestroy( int, char * ); // constructor
of constructor, destructor
11 ~CreateAndDestroy(); function calls. // destructor
12
13 private:
14 int objectID;
15 char *message;
16
17 }; // end class CreateAndDestroy
18
19 #endif
+ 1 // create.cpp
2 // Member-function definitions for class CreateAndDestroy
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // include CreateAndDestroy class definition from create.h
9 #include "create.h"
10
11 // constructor
12 CreateAndDestroy::CreateAndDestroy( Output message to
13 int objectNumber, char *messagePtr ) demonstrate timing of
14 { constructor function calls.
15 objectID = objectNumber;
16 message = messagePtr;
17
18 cout << "Object " << objectID << " constructor runs "
19 << message << endl;
20
21 } // end CreateAndDestroy constructor
22
+ 23 // destructor
24 CreateAndDestroy::~CreateAndDestroy()
25 {
26 // the following line is for pedagogic purposes only
27 cout << ( objectID == 1 || objectID == 6 ? "\n" : ""
);
28 Output message to
29 cout << "Object " << objectID << " destructor
demonstrate timing of runs
" destructor function calls.
30 << message << endl;
31
32 } // end ~CreateAndDestroy destructor
+ 1 // code.cpp
2 // Demonstrating the order in which constructors and
3 // destructors are called.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 // include CreateAndDestroy class definition from create.h
10 #include "create.h" Create variable with global
11 scope.
12 void create( void ); // prototype
13
14 // global object
15 Create local
CreateAndDestroy first( 1, "(global before main)" ); automatic object.
16
17 int main()
18 {
19 cout << "\nMAIN FUNCTION: EXECUTION BEGINS" << endl;
20 Create static local object.
21 CreateAndDestroy second( 2, "(local automatic in main)" );
22
23 static CreateAndDestroy third(
24 3, "(local static in main)" );
25
+ 26 create();
Create local automatic objects.
// call function to create objects
27
28 cout << "\nMAIN FUNCTION: EXECUTION RESUMES" << endl;
29
30 CreateAndDestroy fourth( 4, "(local automatic in main)" );
31
32 cout << "\nMAIN FUNCTION: EXECUTION ENDS" << endl;
33
34 return 0; Create local automatic object.
35
36 } // end main
37 Create local automatic object in
38 // function to create objects function.
39 void create( void )
40 {
41 cout << "\nCREATE FUNCTION: EXECUTION BEGINS" << endl;
42
43 CreateAndDestroy fifth( 5, "(local automatic in create)" );
44
45 static CreateAndDestroy sixth( Create static local object in
46 6, "(local static in create)" );
function.
47 Create local automatic object in
48 CreateAndDestroy seventh(
49 7, "(local automatic in create)" ); function.
50
51 cout << "\nCREATE FUNCTION: EXECUTION ENDS\" << endl;
52
53 } // end function create
+ Object 1 constructor runs (global before main)
Set functions
Perform validity checks before modifying private data
Notify if invalid values
Indicate with return values
Get functions
Query functions
Control format of data returned
+ 1 // time3.h
2 // Declaration of class Time.
3 // Member functions defined in time3.cpp
4
5 // prevent multiple inclusions of header file
6 #ifndef TIME3_H
7 #define TIME3_H
8
9 class Time {
10
11 public: Set functions.
12 Time( int = 0, int = 0, int = 0 ); // default constructor
13
14 // set functions
15 void setTime( int, int, int ); // set hour, minute, second
16 void setHour( int ); // set hour
17 void setMinute( int ); // set minute Get functions.
18 void setSecond( int ); // set second
19
20 // get functions
21 int getHour(); // return hour
22 int getMinute(); // return minute
23 int getSecond(); // return second
24
Assigning objects
Assignment operator (=)
Can assign one object to another of same type
Default: memberwise assignment
Each right member assigned individually to left member
+1 // progtam.cpp
2 // Demonstrating that class objects can be assigned
3 // to each other using default memberwise assignment.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 // class Date definition
10 class Date {
11
12 public:
13 Date( int = 1, int = 1, int = 1990 ); // default
constructor
14 void print();
15
16 private:
17 int month;
18 int day;
19 int year;
20
21 }; // end class Date
22
+ 23 // Date constructor with no range checking
24 Date::Date( int m, int d, int y )
25 {
26 month = m;
27 day = d;
28 year = y;
29
30 } // end Date constructor
31
32 // print Date in the format mm-dd-yyyy
33 void Date::print()
34 {
35 cout << month << '-' << day << '-' << year;
36
37 } // end function print
38
39 int main()
40 {
41 Date date1( 7, 4, 2002 );
42 Date date2; // date2 defaults to 1/1/1990
43
date1 = 7-4-2002
date2 = 1-1-1990
Software reusability
Class libraries
Well-defined
Carefully tested
Well-documented
Portable
Widely available
Speeds development of powerful, high-quality software
Rapid applications development (RAD)
Resulting problems
Cataloging schemes
Licensing schemes
Protection mechanisms