0% found this document useful (0 votes)
44 views82 pages

Bject Riented Rogramming: Bjects and Lasses

The document discusses object oriented programming and key concepts like classes, objects, encapsulation, inheritance, and polymorphism. It provides an example of implementing a time abstract data type using a Time class with data members like hour, minute, second and member functions to set and display time. The Time class makes use of concepts like constructors, destructors, and defining member functions outside the class.

Uploaded by

Muhammad Haider
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views82 pages

Bject Riented Rogramming: Bjects and Lasses

The document discusses object oriented programming and key concepts like classes, objects, encapsulation, inheritance, and polymorphism. It provides an example of implementing a time abstract data type using a Time class with data members like hour, minute, second and member functions to set and display time. The Time class makes use of concepts like constructors, destructors, and defining member functions outside the class.

Uploaded by

Muhammad Haider
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

OBJECT ORIENTED

PROGRAMMING
OBJECTS AND CLASSES

Imran Siddiqi
Dept of CS
Bahria University, Islamabad
[email protected]
1
STRUCTURED PROGRAM

MAIN PROGRAM DATA

FUNCTION 1 FUNCTION 2 FUNCTION 3

FUNCTION 4 FUNCTION 5

2
OBJECT ORIENTED PROGRAM
Object 1 Object 2

Data Data

Function Function

Object 3

Data

Function
3
THE ABSTRACT DATA TYPE (ADT)

The concept of abstraction means:


 We know what a data type can do
 How it is done is hidden for the user

With an ADT users are not concerned with how the task is
done but rather with what it can do.

4
DATA ABSTRACTION
 We don’t really care how an object is implemented.
 As long as a car works, we don’t care that it includes 4-
cylinder engine, steel wheels, and 12V accumulator. We
don’t care that the engine runs at 3,000 RPM and that the
plugs make 700 ignitions per second.

 As long as cars exhibit some similar interface, we can


drive them.

5
THE ABSTRACT DATA TYPE (ADT)

The Abstract Data Type (ADT) is:


 A data declaration packaged together with the operations that are
meaningful for the data type.
 In other words, we encapsulate the data and the operations on the
data, and then we hide them from the user.

Declaration of data
Declaration of operations
Encapsulation of data and operations
6
7
8
FUNDAMENTAL CONCEPTS IN OOP (PIIE)
 Polymorphism
 Instantiation

 Inheritance

 Encapsulation

9
FUNDAMENTAL CONCEPTS IN OOP
 Encapsulation
 Data Abstraction
 Information hiding

 Instantiation
 Making instances of classes – Objects

 Inheritance
 Code reusability
 Is-a vs. has-a relationships

 Polymorphism 10
 Dynamic method binding
ENCAPSULATION
 Encapsulates data (attributes) and functions
(behavior) into packages called classes

 Data abstraction
 Class objects communicate across well-defined interfaces
 Implementation details hidden within classes themselves

 Information Hiding
 Restricting access to some data

11
IMPLEMENTING THE TIME ABSTRACT DATA
TYPE WITH A CLASS
 Classes
 Model objects
 Attributes (data members)
 Behaviors (member functions)

 Defined using keyword class


 Member access specifiers
 public:
 Accessible wherever object of class in scope
 private:
 Accessible only to member functions of class
 protected:
 Wait for a couple of weeks 

12
IMPLEMENTING THE TIME ABSTRACT DATA
TYPE WITH A CLASS
class Time {

private:

// Data Members here (In general)

public:
// Member Functions here (In general)

13
}; // end class Time
IMPLEMENTING THE TIME ABSTRACT DATA
TYPE WITH A CLASS
class Time {

private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 – 59

public:
// Member Functions here

}; // end class Time


14
IMPLEMENTING THE TIME ABSTRACT DATA
TYPE WITH A CLASS
class Time {

private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 – 59

public:
void displayTime(){
cout << hour;
cout << min;
cout << sec;
}
15

}; // end class Time


IMPLEMENTING THE TIME ABSTRACT DATA
TYPE WITH A CLASS
class Time {
private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 – 59
public:
void displayTime(){
cout << hour;
cout << min;
cout << sec;
}
void setTime(){
hour = 12; User specified values
min = 0; should be set
sec = 0;
16
}
}; // end class Time
IMPLEMENTING THE TIME ABSTRACT DATA
TYPE WITH A CLASS
class Time {
private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 – 59
public:
void displayTime(){
cout << hour;
cout << min;
cout << sec;
}
void setTime(int h, int m, int s){
hour = h;
min = m;
sec = s;
17
}
}; // end class Time
IMPLEMENTING THE TIME ABSTRACT DATA
TYPE WITH A CLASS
Object

int main(){

Time t;

Class name return 0;


}

‘t’ is an object of class Time


18
IMPLEMENTING THE TIME ABSTRACT DATA
TYPE WITH A CLASS

int main(){
t
Time t; hour ???
min ???
sec ???
return 0;
}

19
IMPLEMENTING THE TIME ABSTRACT DATA
TYPE WITH A CLASS

int main(){
t
Time t; hour ???
min ???
t.hour = 12;
sec ???

return 0;
}

20
IMPLEMENTING THE TIME ABSTRACT DATA
TYPE WITH A CLASS

int main(){
t
Time t; hour 12
t.setTime(12,0,0); min 0
sec 0

return 0;
}

21
IMPLEMENTING THE TIME ABSTRACT DATA
TYPE WITH A CLASS

int main(){ t1
hour 12
min 0
Time t1, t2; sec 0
t1.setTime(12,0,0);
t2.setTime(14,10,0); t2
hour 14
return 0; min 10
sec 0
}
22
CONSTRUCTOR

 Special member function


 Initializes data members
 Same name as class

 Called (automatically) when object instantiated


 Several constructors
 Function overloading
 No return type

23
class Time {
private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 – 59
public:
Time(){ // Constructor
hour = 0;
min = 0;
sec = 0;
}

void displayTime(){
cout << hour;
cout << min;
cout << sec;
}
void setTime(int h, int m, int s){
hour = h;
min = m;
sec = s; 24
}
}; // end class Time
CONSTRUCTOR

int main(){
t
Time t; hour 0
min 0
sec 0
return 0;
} Constructor is called automatically
And data members are initialized

25
class Time {
private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 – 59
public:
Time(){ // No-Argument Constructor
hour = 0;
min = 0;
sec = 0;
}

Time(int h, int m, int s){// Parameterized Constructor

hour = h;
min = m;
sec = s;
}
}; // end class Time
26
DESTRUCTOR

 Same name as class


 Preceded with tilde (~)
 No arguments
 Cannot be overloaded

 Performs “termination housekeeping”

27
class Time {
private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 – 59
public:
Time(){ // Constructor
hour = 0;
min = 0;
sec = 0;
}
~Time(){ // Destructor

}; // end class Time

28
INSTANTIATING OBJECTS
 Objects of class
 After class definition
 Class name new type specifier
 Object, array, and pointer declarations

 Examples:

Time sunset; // object of type Time


Time arrayOfTimes[ 5 ]; // array of Time objects
Time *pointerToTime; // pointer to a Time object

29
MEMBER FUNCTIONS DEFINED OUTSIDE
THE CLASS

 Binary scope resolution operator (::)


 “Ties” member name to class name
 Uniquely identify functions of particular class
 Different classes can have member functions with
same name
 Format for defining member functions
ReturnType ClassName::MemberFunctionName( ){

}
 Does not change whether function public
or private
 Member functions defined inside class
30
 Do not need scope resolution operator
// Time class.
#include <iostream>
#include <iomanip>
using namespace std;

// Time abstract data type (ADT) definition


class Time {
private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 - 59
public:
Time(); // constructor
void setTime( int, int, int );
void printTime();
31
}; // end class Time
// Time constructor initializes each data member to zero and
// ensures all Time objects start in a consistent state
Time::Time()
{
hour = minute = second = 0;

// set new Time value using universal time, perform validity


// checks on the data values and set invalid values to zero

void Time::setTime( int h, int m, int s )


{
hour = ( h >= 0 && h < 24 ) ? h : 0;
minute = ( m >= 0 && m < 60 ) ? m : 0;
second = ( s >= 0 && s < 60 ) ? s : 0;

}
32
void Time::printTime()
{
cout << setw( 2 ) << hour << ":“
<< setw( 2 ) << minute << ":“
<< setw( 2 ) << second;

} // end function printTime

33
int main()
{
Time t; // instantiate object t of class Time
cout << "The initial time is ";
t.printTime(); // 00:00:00

t.setTime( 13, 27, 6 ); // change time

// output Time object t's new values


cout << "\n\nTime after setTime is ";
t.printTime(); // 13:27:06

t.setTime( 99, 99, 99 ); // attempt invalid settings

// output t's values after specifying invalid values


cout << "\n\nAfter attempting invalid settings:“
<< "\nUniversal time: ";

t.printTime(); // 00:00:00
return 0;
}
34
ADVANTAGES OF USING CLASSES
 Simplify programming
 Interfaces
 Hide implementation
 Software reuse (Later Weeks)
 Composition (Aggregation)
 Class objects included as members of other classes
 Inheritance
 New classes derived from old

35
EXAMPLE 2

Write a program that reads a


temperature (either Fahrenheit or
Celsius), and displays that same
temperature

36
PRELIMINARY ANALYSIS
 An object must be directly representable using a
single type
 A temperature has two attributes:
 its magnitude (a double), and
 its scale (a character)

 When an object cannot be directly represented by


any of the available types, build a class!

37
BUILDING CLASSES
 Begin by defining variables to store the
attributes of the object being represented (a
temperature)

double magnitude;
char scale;

38
BUILDING CLASSES
We then wrap these variables in a class declaration:
class Temperature
{
public:
private:
double magnitude;
char scale;
};

 Declaring this class does not allocate memory for a


Temperature
 It just tells the compiler what temperature is and
what are its attributes 39
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 40
DEFINING AN OBJECT
A programmer can now write:
Temperature aTemp;

Object aTemp can be visualized as follows:

aTemp magnitude

scale

The data members magnitude and scale within aTemp are


uninitialized
41
CLASSES VERSUS OBJECTS
 An object has the same relationship to a class as a
variable has to a data type
 An object is said to be an instance of a class

 As you don’t assign values to types rather to


variables
int = 5; //wrong
int x = 5; //right
 Similarly an object of a class has to be created before
it can be assigned any values
Temperature aTemp;
42
MEMBER FUNCTIONS
 Operations on a class object are usually implemented
as class member functions
 A call to a member function:
Object.Function()
 Example:
aTemp.display()
void Temperature::display()
{
cout << “Magnitude:” <<magnitude ;
cout <<“ ,Scale:” << scale;
}
43
MEMBER FUNCTIONS
class Temperature
{
public:
void display();
private:
double magnitude;
char scale;
};
• By declaring the prototype within the class, we tell
the compiler that class Temperature has a function
member named display()

44
CONSTRUCTOR
Temperature::Temperature()
{
magnitude = 0.0;
scale = ‘C’;
}

• 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 Temperature())
• As a member function of class Temperature, its full
name is Temperature::Temperature()
45
CONSTRUCTOR
class Temperature
{
public:
Temperature();
void display();
private:
double magnitude;
char scale;
};

46
OBJECT DEFINITIONS

A programmer can now write:

Temperature aTemp;
and object aTemp can be visualized as follows:

aTemp magnitude 0.0

scale C

• The class constructor is automatically called whenever


a class object is defined
47
48
PARAMETERIZED CONSTRUCTOR
Temperature::Temperature(double mag, char sc)
{

magnitude = mag;
scale = sc;
}

class Temperature
{
public:
Temperature();
Temperature(double mag, char sc);
void display();
private:
double magnitude;
char scale; 49

};
OBJECT DEFINITIONS
A programmer can now write:
Temperature temp1, temp2(98.6, ‘F’);
And temp1 and temp2 are defined as follows:

temp1 magnitude 0.0 temp2 magnitude 98.6

scale C scale F

• The compiler uses the number of arguments in a


declaration to decide which constructor to use in
initializing an object
50
DRIVER PROGRAM

int main()
{
Temperature temp1, temp2(98.6, ‘F’);

temp1.display(); // displays
// Magnitude:0,Scale C
cout << endl;
temp2.display(); // displays
// Magnitude:98.6,Scale:F
}

51
PLACING FUNCTION DEFINITION WITHIN CLASS DEFINITION

class Temperature
{
private:
double magnitude;
char scale;
public:
Temperature() {
magnitude = 0.0;
scale = ‘C’;
}
void display() {
cout << “Magnitude:” <<magnitude ;
cout <<“ ,Scale:” << scale;
}
};

52
CONSTRUCTOR – ANOTHER SYNTAX
class Temperature
{
private:
double magnitude;
char scale;
public:
Temperature(): magnitude (0.0), scale(‘C’)
{ /*empty body*/ }

Temperature(double mag, char sc):


magnitude(mag),scale(sc)
{/*empty body*/}

void display()

}; 53
NO-ARG CONSTRUCTOR
 If you don’t explicitly define any constructors, the
compiler automatically generates a default constructor
that takes no arguments

 In case you do not define any constructors and simply


create a Temperature object

Temperature aTemp;

 The compiler will call a default constructor which does


not, however, assign any values to the data members

 But once you’ve defined even one kind of constructor


(may be a 2-arg constructor),the compiler will no longer
54
create a default no-arg constructor for you
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 the default
parameter list
 This rule helps the compiler determine which arguments to
assign values to in a function call

55
USING DEFAULT PARAMETERS
 We can “combine” two functions (constructor without
parameters and constructor with parameters) using
default parameters of C++
 The prototype in the class definition would be
Temperature(double mag=0.0, char sc='C');
 The function definition would be
Temperature::Temperature(double mag,char sc)
{
magnitude = mag;
scale = sc;
}
56
DRIVER PROGRAM
int main()
{
Temperature t1;
Temperature t2(100.0);
Temperature t3(100.0,'F');
Temperature t4 = Temperature(37.0,’C’);
t1.display();
t2.display();
t3.display();
getch();
return 0;
} 57
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, pointer to object

 File scope
 Nonmember functions
58
CLASS SCOPE AND ACCESSING CLASS
MEMBERS
 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
 Variables only known to function they are defined in
 Variables are destroyed after function completion

59
CLASS SCOPE AND ACCESSING CLASS
MEMBERS
class Test
{
private:
int x;
public:
Test(){x = 5;};
void Function()
{ int x=1;;
cout << x << endl;
cout << Test::x << endl;
}
};
void main()
{ Test t;
60
t.Function();
}
CLASS SCOPE AND ACCESSING CLASS
MEMBERS
 Operators to access class members
 Identical to those for structs
 Dot member selection operator (.)
 Object
 Arrow member selection operator (->)
 Pointers

61
EXAMPLE
#include <iostream>

using namespace std;

class Count { Data member x public to


illustrate class member access
public: operators; typically data
int x; members are private.

void print() {
cout << x << endl;
}

}; // end class Count

62
int main() Use dot member selection
operator for counter object.
{
Count counter; // create counter object
Count *counterPtr = &counter; // create pointer to counter

cout << "Assign 1 to x and print using the object :";


counter.x = 1; // assign 1 to data member x
counter.print(); // call member function print

cout << "Assign 2 to x and print using a pointer: ";


counterPtr->x = 2; // assign 2 to data member x
counterPtr->print(); // call member function print

return 0; Use arrow member selection


operator for counterPtr
} // end main pointer to object.

Assign 1 to x and print using the object: 1 63


Assign 2 to x and print using a pointer: 2
SEPARATING INTERFACE FROM
IMPLEMENTATION
 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

64
// File : time1.h
// Declaration of class Time.
// Member functions are defined in time1.cpp4

// prevent multiple inclusions of header file


#pragma once

// Time abstract data type definition


class Time {
public:
Time(); // constructor
void setTime( int, int, int ); // set Time
void printTime(); // print time
private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 – 59
int second; // 0 – 59
}; // end class Time 65
// File: time1.cpp
// Member-function definitions for class Time.
#include <iostream>
#include <iomanip> Include header file
using namespace std; time1.h.
// include definition of class Time from time1.h
#include "time1.h"

// Time constructor initializes each data member to zero.


Time::Time()
{
hour = minute = second = 0;

} // end Time constructor

66
// Set new Time value using universal time. Perform validity
// checks on the values. Set invalid values to zero.

void Time::setTime( int h, int m, int s )


{
hour = ( h >= 0 && h < 24 ) ? h : 0;
minute = ( m >= 0 && m < 60 ) ? m : 0;
second = ( s >= 0 && s < 60 ) ? s : 0;
} // end function setTime

// print Time in universal format


void Time::printTime()
{
cout << setw( 2 ) << hour << ":“
<< setw( 2 ) << minute << ":“
<< setw( 2 ) << second;
67
} // end function printTime
// Driver Program
// Program to test class Time.
#include <iostream>
using namespace std;

// include definition of class Time from time1.h


#include "time1.h"
int main()
{
Time t; // instantiate object t of class Time

// output Time object t's initial values


cout << "The initial time is ";
t.printTime(); // 00:00:00

t.setTime( 13, 27, 6 ); // change time


// output Time object t's new values
cout << "\n\nTime after setTime is "; 68
t.printTime(); // 13:27:06
t.setTime( 99, 99, 99 ); // attempt invalid settings

// output t's values after specifying invalid values


cout << "\n\nAfter attempting invalid settings:“
<< "\ntime is: ";
t.printTime(); // 00:00:00

cout << endl;

return 0;

} // end main

69
CONTROLLING ACCESS TO MEMBERS
 Class member access
 Default private
 Explicitly set to private, public, protected

 struct member access


 Default public
 Explicitly set to private, public, protected

 Access to class’s private data


 Controlled with access functions (accessor methods)
 Get function
 Read private data

 Set function
 Modify private data
70
USING SET AND GET FUNCTIONS
 Set functions
 Perform validity checks before modifying private
data
 Notify if invalid values

 Get functions
 “Query” functions

71
// File: time3.h

#pragma once
class Time {

public:
Time( int h = 0, int m = 0, int s = 0 );// default constructor

// set functions
void setTime( int, int, int ); // set hour, minute, second
void setHour( int ); // set hour
void setMinute( int ); // set minute
void setSecond( int ); // set second

// get functions
int getHour(); // return hour
72
int getMinute(); // return minute
int getSecond(); // return second
void printTime(); // output Time

private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 – 59
int second; // 0 – 59

}; // end clas Time

73
// File: time3.cpp
// Member-function definitions for Time class.
#include <iostream>
#include <iomanip>
using namespace std;
// include definition of class Time from time3.h
#include "time3.h“

// constructor function to initialize private data;


// calls member function setTime to set variables;
// default values are 0 (see class definition)
Time::Time( int hr, int min, int sec )
{
setTime( hr, min, sec );

} // end Time constructor

74
// set hour, minute and second values
void Time::setTime( int h, int m, int s )
{
setHour( h );
setMinute( m );
setSecond( s );
}
// set hour value
void Time::setHour( int h )
{
hour = ( h >= 0 && h < 24 ) ? h : 0;
}

// set minute value


void Time::setMinute( int m )
{
minute = ( m >= 0 && m < 60 ) ? m : 0;
75
}
// set second value
void Time::setSecond( int s )
{
second = ( s >= 0 && s < 60 ) ? s : 0;
}

// return hour value


int Time::getHour()
{
return hour;
}
// return minute value
int Time::getMinute()
{
return minute;
}

76
// return second value
int Time::getSecond()
{
return second;
}

// print Time
void Time::printTime()
{
cout << setw( 2 ) << hour << ":“
<< setw( 2 ) << minute << ":“
<< setw( 2 ) << second;
}

77
// Driver Program
// Demonstrating the Time class set and get functions
#include <iostream>
using namespace std;
#include "time3.h“

int main()
{
Time t; // create Time object

t.setHour( 17 ); // set hour to valid value


t.setMinute( 34 ); // set minute to valid value
t.setSecond( 25 ); // set second to valid value

// use get functions to obtain hour, minute and second


cout << “Current values:\n"
<< " Hour: " << t.getHour()
<< " Minute: " << t.getMinute()
<< " Second: " << t.getSecond();
return 0;
78
} // end main
USING THE ASSIGNMENT OPERATOR WITH
OBJECTS
 Assigning objects
 Assignment operator (=)
 Can assign one object to another of same type
 Default: member-wise assignment

 Each right member assigned individually to left member

79
// Demonstrating that class objects can be assigned
// to each other using default member-wise assignment.
#include <iostream>
using namespace std;

class Date {
public:
Date( int m = 1, int d = 1, int y = 1990 );
void print();

private:
int month;
int day;
int year;

}; // end class Date

80
// Date constructor
Date::Date( int m, int d, int y )
{
month = m;
day = d;
year = y;

}
// print Date in the format mm-dd-yyyy
void Date::print()
{
cout << month << '-' << day << '-' << year;

}
int main()
{
Date date1( 7, 4, 2002 );
81
Date date2; // date2 defaults to 1/1/1990
cout << "date1 = ";
date1.print();
cout << "\ndate2 = ";
date2.print();

date2 = date1; // default memberwise assignment

cout << "\n\nAfter default memberwise assignment,date2 = ";


date2.print();
cout << endl;

return 0;

} // end main

date1 = 7-4-2002
date2 = 1-1-1990
82
After default memberwise assignment, date2 = 7-4-2002

You might also like