Sie sind auf Seite 1von 61

Object Oriented Programming with C++

Mekelle Institute of Technology


Department of Computer Science and Engineering
Kifle B.N
(kifle.berhane@mu.edu.et)
Room#-100
Course Objectives
 Understand Concept of Object Oriented programming
language
 Understand benefits of OOP over POP

 Introduce the concepts of C++ programming

 Enable students to develop various applications by applying

the concept of OOP and different features of C++


programming language

1-1
Contents

 Introduction to OOP
 Message Passing

 OOP vs POP

 Benefits of OOP

 Introduction to C++

 Structures

 Manipulators

 Summary

1-2 2
Introduction to OOP
 The motive for OOP:
 As programming projects became large and more complicated, step
by step programming did not work very well. The problem is
complexity.
 Because of this complexity, programs are prone to error, and
software errors can be expensive and even life threatening.
 One of the programming innovations made to deal with the problem
of complexity is Object Oriented Programming (OOP)
 What is OOP?
 OOP is a programming method based on real world entities (objects)
to design and build software applications.
 It is a problem solving approach where all computations are carried
out using objects.
 It views a programming problem as a group of objects that have
certain properties and can take certain actions, instead of series of
steps to be carried out.

1-3
Object-Oriented Programming
 Key Object-Oriented Systems Concepts
 Abstraction
 Classes(Objects ,Methods and Variables)
 Encapsulation
 Inheritance
 Polymorphism
 Message Passing

1-4
Abstraction
 An emphasis on what an object is (properties) or does (method) rather than how it
works.
 Suppression of details or hiding of irrelevant details.

 Thus, it is the primary means of managing complexity in large programs.

 Data abstraction refers to providing only essential information to the outside world and
hiding their background details,
 Data abstraction is a programming (and design) technique that relies on the
separation of interface and implementation.
 You can turn on and off, change the channel, adjust the volume, and add external
components such as speakers, BUT you do not know its internal details, that is, you do
not know how it receives signals over the air or through a cable, how it translates them,
and finally displays them on the screen.
 Thus, we can say a television clearly separates its internal implementation from
its external interface and you can play with its interfaces like the power button,
channel changer, and volume control without having zero knowledge of its
internals.

1-5
Abstraction
 In C++, we use classes to define our own abstract data types (ADT).
You can use the cout object of class ostream to stream data to
standard output like this :
#include <iostream>
using namespace std;
int main()
{
cout << "Hello C++" <<endl;
return 0;
}
Here, you don't need to understand how cout displays the text on the
user's screen. You need to only know the public interface and the
underlying implementation of ‘cout’ is free to change.
1-6
Data Abstraction Examples
 Any C++ program where you implement a class with public and private members is an
example of data abstraction. Consider the following example .
#include <iostream> // interface to outside world
using namespace std; int getTotal()
class Adder {
{ return total;
public: };
// constructor private:
Adder(int i = 0) // hidden data from outside
{ world
total = i; int total;
} };
// interface to outside world
void addNum(int number)
{
total += number;
1-7 }
Data Abstraction Examples
int main()
{
Adder a; // a is an object of Adder type
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;
}
 When the above code is compiled and executed, it produces: Total 60. The above
class adds numbers together, and returns the sum. The public members -
addNum and getTotal are the interfaces to the outside world and a user needs to
know them to use the class. The private member total is something that the user
doesn't need to know about, but is needed for the class to operate properly.

1-8
What is an Object?
Real-world objects have attributes and behaviors.

Examples:
 Dog

 Attributes: breed, color, hungry, tired, etc.


 Behaviors: eating, sleeping, etc.
 Bank Account
 Attributes: account number, owner, balance
 Behaviors: withdraw, deposit

1-9
Software Objects
Writing software often involves creating a computational model
of real-world objects and processes.

 Object-oriented programming is a methodology that gives


programmers tools to make this modeling process easier.
 Software objects, like real-world objects, have attributes and

behaviors.
 Your best bet is to think in terms as close as possible to the

real world; trying to be tricky or cool with your system is


almost always the wrong thing to do.

1 - 10
Software Objects - Cont’d
In traditional programming languages (Fortran, Cobol, C, etc)
data structures and procedures are defined separately.
 In object-oriented languages, Bank
they are defined together. Account
 An object is a collection of
Account
attributes and the behaviors
Account
that operate on them.
 Variables in an object are called number:
attributes. balance:
 Procedures associated with an deposit()
object are called methods.
withdraw()

1 - 11
Classes
The definitions of the attributes and methods of an object are
organized into a class. Thus, a class is the generic definition
for a set of similar objects (i.e. Person as a generic definition
for Hagos, Abraha and Senay)

 A class can be thought of as a template used to create a set


of objects.
 A class is a static definition; a piece of code written in a

programming language.
 One or more objects described by the class are instantiated

at runtime.
 The objects are called instances of the class.

1 - 12
Classes - Cont’d
 Each instance will have its own distinct set of attributes.
 Every instance of the same class will have the same set of

attributes;
 every object has the same attributes but,
 each instance will have its own distinct values for those
attributes.

1 - 13
Bank Example
 The "account" class describes the
attributes and behaviors of bank class: Account
accounts.
number:
 The “account” class defines two

state variables (account number balance:


and balance) and two methods
deposit()
(deposit and withdraw).
withdraw()

1 - 14
Bank Example - Cont’d
 When the program runs there will Instance #1
be many instances of the account number: 054
class.
balance: $19
 Each instance will have its own

account number and balance Instance #2


(object state) number: 712
 Methods can only be invoked .
balance: $240

Instance #3

number: 036

balance: $941

1 - 15
Class student
Class student
{
string Name;
string ID;
int Year;
string dept;
float result;
Public:
UpdatestudInfo();
Calcstuderesult();
}; // example of a class specification
student thirdyearstud; //thirdyearstud is an example of an object
of type student
1 - 16
Encapsulation
When classes are defined, programmers can specify that
certain methods or state variables remain hidden inside the
class.
 These variables and methods are Visible Methods
accessible from within the class, but not
Hidden
accessible outside it. State
 The combination of collecting all the
Variables
and
attributes of an object into a single class Methods
definition, combined with the ability to hide
some definitions and type information Visible Variables
within the class, is known as
encapsulation.
Class
Definition
1 - 17
Graphical Model of an Object
Instance balance()
variables

withdraw() theBalance deposit()


acctNumber

Methods
accountNumber()

State variables make up the nucleus of the object. Methods


surround and hide (encapsulate) the state variables from the
rest of the program.

1 - 18
Instance Methods and Instance Variables
The methods and variables described in this module so far are
know as instance methods and instance variables.

 These state variables are associated with the one instance of


a class; the values of the state variables may vary from
instance to instance.
 Instance variables and instance methods can be public or

private.
 It is necessary to instantiate (create an instance of) a class to

use it’s instance variables and instance methods.

1 - 19
Class Methods and Class Variables
In addition to instance methods and instance variables, classes
can also define class methods and class variables.

 These are attributes and behaviors associated with the class


as a whole, not any one instance.
 Class variables and class methods can be public or private.

 It is not necessary to instantiate a class to use it’s class

variables and class methods.

1 - 20
Class Variables
 A class variable defines an attribute of an entire class.
 In contrast, an instance variable defines an attribute of a

single instance of a class.


instance
variables

Account
class
variable count: 3 num: 036
num: 054 num: 712
bal: $19 bal: $240 bal: $941
printCount()
Class
method

1 - 21
Inheritance
The advantage of making a new class a subclass is that it will
inherit attributes and methods of its parent class (also called
the superclass).

 Subclasses extend existing classes in three ways:


 By defining new (additional) attributes and methods.
 By overriding (changing the behavior) existing attributes and
methods.
 By hiding existing attributes and methods.

1 - 22
Subclasses
When a new class is developed a programmer can define it to
be a subclass of an existing class.
 Subclasses are used to define special cases, extensions, or

other variations from the originally defined class.


Examples:
Generic Class for Terrier is derived
 Terrier can be defined as a Dog from Dog
subclass of Dog. With general
attributes and Specific Class for
 SavingsAccount and
behaviors for all Terrier
CheckingAccount can be dogs. With new attributes
derived from the Account and behaviors
class (see following slides). specific to the
Terrier breed.
1 - 23
New Account Types - Cont’d
Suppose we define SavingsAccount and CheckingAccount
as two new subclasses of the Account class.

class SavingsAccount
class Account { extends Account {
method acctNum() {…} method rate() {…}
method balance() {…} }
method deposit() {…}
method withdraw() {…}
class CheckingAccount
}
extends Account {
method withdraw() {…}
}

1 - 24
New Account Types - Cont’d
Account SavingsAccount CheckingAccount

acctNum() acctNum() acctNum()


balance() balance() balance()
deposit() deposit() deposit()
withdraw() withdraw() withdraw()

rate() withdraw()

No new code has to be written for deposit() and other


methods, they are inherited from the superclass.

1 - 25
Polymorphism
 The ability to request the same operations to be performed by
a wide range of different types of things.
 Same operation can have different functionalities

 The same message sent to different types of objects results

in:
 execution of behavior that is specific to the object and,
 possibly different behavior than that of other objects receiving
the same message.
 Example: the message draw() sent to an object of type
Square and an object of type Circle will result in different
behaviors for each object.

1 - 26
Polymorphism – Cont’d
There are many forms of Polymorphism in object-oriented
languages, such as:

 True Polymorphism: Same method signature defined for different


classes with different behaviors (i.e. draw() for the Classes Circle
and Square)
 Parametric Polymorphism: This is the use of the same method

name within a class, but with a different signature (different


parameters).
 Overloading: This usually refers to operators (such as +,-,/,*, etc)

when they can be applied to several types such as int, floats,


strings, etc.
 Overriding: This refers to the feature of subclasses that replace

the behavior of a parent class with new or modified behavior.


1 - 27
Messages
 Messages are information/requests that objects send to other
objects (or to themselves).
 Message components include:

 The name of the object to receive the message.


 The name of the method to perform.
 Any parameters needed for the method.

Manager Employee

Message
To: Employee
Method: getHired
Parameters: salary = $45,000, start_date = 10/21/99
1 - 28
Benefits of Messages
Message passing supports all possible interactions between
two objects.

 Message passing is the mechanism that is used to invoke a


method of the object.
 Objects do not need to be part of the same process or on the

same machine to interact with one another.


 Message passing is a run-time behavior, thus it is not the

same as a procedure call in other languages (compile-time).


 The address of the method is determined dynamically at run-
time, as the true type of the object may not be known to the
compiler.

1 - 29
POP vs OOP
Procedure Oriented Object Oriented Programming
programming(POP) (OOP)
 Program is divided into small  Program is divided into parts
parts called functions. called objects
 Important things are functions  Important thing is data rather than
and sequence of actions procedures or functions
 Follows Top Down approach  Follows Bottom Up approach
 Does not have any access  has access specifiers named
specifier Public, Private, Protected
 There is no data hiding so there  Provides data hiding so more
is less security security
 Overloading not possible  Overloading is possible
 Suitable for larger programs  Suitable for larger programs
 Examples: C, VB, FORTRAN,  Examples: C++, JAVA, VB.NET,
Pascal C#.NET.

1 - 30
POP

MAIN PROGRAM GLOBAL DATA

FUNCTIO FUNCTION FUNCTION


N1 2 3

FUNCTION FUNCTION
4 5

1 - 31
OOP

Object 2
Object 1

Data1 Data2

Functio Functio
n1 n2

Object 3

Data3

Functio
n3

1 - 32
Benefits of Object-oriented programming
 Save development time and cost by reusing code –
once an object class is created it can be reused
 Easier debugging – classes can be tested independently

– reused objects have already been tested


 Through inheritance, we can eliminate redundant code

and extend the use of existing


 The principle of data hiding helps the programmer to build

secure programs that cannot be invaded by code in other


parts of the program

1 - 33
C++ Programming Language Intro
 C++ is derived from C language to manage complexity
that C could not handle.
 The major changes are addition of classes, inheritance,

exception handling, encapsulation…


 From the OOP languages, C++ is by far the most widely

used.
 Java lacks certain features—such as pointers, templates,

and multiple inheritances


 In general, everything that exists in C is supported in

C++, C is subset of C++

1 - 34
Similarities between C and C++
 same built-in data types
 same compiler preprocessor

 handles #include, #define


 same built-in operators (+-/*……)
 Same built-in control structures

 if, for, while, switch ….


 they have function “main” to determine where the
program starts
 functions are defined the same way

1 - 35
Differences C vs C++
C Programming C++ Programming

 data is manipulated with  Classes used to model


functions behavior of data objects
 Can’t have two or more with  Two or more functions may

the same function names have the same name


 operators cannot be redefined  operators can be redefined to

to do other things do other things


 C uses “malloc” and “free” for  C++ uses “new” and “delete”

dynamic memory management for dynamic memory


 No user defined data types management
 Can have a user defined data

types(classes)

1 - 36
Main Application areas
 C programming is applicable in system programming,
language compilers, databases, assemblers…
 C++ is also applicable in system programming,

development of OOP based application softwares.


 Most of the time, the OS developers are taking the

advantages among different languages.


 Like using C to write hardware level code, using C++ to
write memory management, and using Java/C# to write
GUI.

1 - 37
Basic C++ Program Construction
//Let’s look at a very simple C++ program.
#include <iostream> //1. preprocessor
using namespace std; //2. using directive
int main() // 3. main function and parentheses
{ //4. braces
cout << “My first C++ program\n”; //5. program statement
return 0;
}
Let’s discuss them one by one

1 - 38
Preprocessor Directive
 #include <iostream> is called a preprocessor directive.
 The preprocessor directive #include tells the compiler to

include header file (iostream) into your source file


 header file IOSTREAM has everything needed for basic

input/output operations
 iostream contains code to define cout and cin identifiers,

<< and >> operators, endl…


 Without these declarations, the compiler won’t recognize

these identifiers and operators

1 - 39
The using Directive
 A namespace is designed to differentiate similar functions,
classes, variables with the same name available in different
libraries.
 It is a scope identifier

 The directive using namespace std; says that all the program
statements that follow are within the std namespace.
 cout, cin and a lot of other things are defined in std
namespace
 If we don’t use the using directive, we would need to add the
std name to every program elements.
 For example, std::cout << “Every age has a language of its
own.”;
 Q: what is the necessity of including “using namespace std” if
everything is there in <iostream> for cout, cin etc..?
1 - 40
Ans
 #include<iostream> copies codes for cout, cin, endl and other
identifiers and operators into your source file.
 The namespace helps us to identify these identifiers and operators in
which context(scope) we are referring. To avoid naming class with
names defined by the user or other libraries.
 Example:
namespace name1
{
void print() {
}
}
namespace name2 {
void print() {
}
// function name1::print()
// function name2::print()

1 - 41
I/O Statements
 Standard input and output library help interact with the
user by printing messages on the screen and getting the
user's input from the keyboard.
 C++ uses a convenient abstraction called streams to

perform input and output operations in sequential media


such as the screen or the keyboard.
 A stream is an object where a program can either insert

or extract characters to/from it.

1 - 42
Standard Output (cout)
 By default, the standard output of a program is the
screen, and the C++ stream object defined to access it is
cout.
 cout is used in conjunction with the insertion operator, <<

 E.g: cout << 120; // prints number 120 on screen

 The << operator inserts the data that follows it into the

stream preceding it.


 In the example above it inserts the numerical constant

120 into the standard output stream cout.


 The stream cout prints the number on the screen

1 - 43
Standard Input (cin)
 The standard input device is usually the keyboard.
 Handling the standard input in C++ is done by

applying extraction >> operator on the cin stream.


 Example: int age;

 cin >> age; //waits for an input from cin (the

keyboard) in order to store it in variable age


 cin can only process the input from the keyboard

once the RETURN key has been pressed.

1 - 44
cin and string
 We can use cin to get strings with the extraction operator (>>) as we do with
fundamental data type variables: cin >> mystring;
 cin extraction stops reading as soon as if finds any blank space

 In order to get entire lines, we can use the function getline()

 Example:

int main ()
{ string mystr;
cout << "What's your name? ";
getline (cin, mystr);
cout << "Hello " << mystr << ".\n";
cout << "What is your favorite team? ";
getline (cin, mystr);
cout << "I like " << mystr << " too!\n";
return 0;
}
1 - 45
stringstream
 The standard header file <sstream> defines a class called string stream
that allows a string-based object to be treated as a stream.
 Helps perform extraction or insertion operations from/to strings, which is
especially useful to convert strings to numerical values and vice versa.
 For example: to extract an integer from a string we can write:

string mystr ("1204"); // declared a string object with a value of “1204”


int myint;
stringstream(mystr) >> myint; // gets numerical value indirectly
 It is like an input/output file stream. Can read from or write to it

sstream ss;
string mystring;
ss<<mystr; //writing to it
ss>>mystring; //reading from it

1 - 46
Structure
 A structure is a collection of simple variables of different types
(int, float...).
 This is unlike array in which all the variables must be the

same type.
 The data items in a structure are called the members of the

structure.
 In C++ programmers, structures are one of the two important

building blocks in the understanding of objects and classes.


 A structure is a collection of data, while a class is a

collection of both data and functions. They have similar


syntax
 So by learning about structures we’ll be paving the way for an

understanding of classes and objects.

1 - 47
Structure…

1 - 48
Example: records of parts in company
struct part //declare a structure
{ int modelnumber; //ID number of part
int partnumber; // role number of part
float cost; //cost of part
};
int main() {
part part1; //define a structure variable
part1.modelnumber = 6244; //give values to structure members
part1.partnumber = 373;
part1.cost = 217.55F; //display structure members
cout << “Model “ << part1.modelnumber;
cout << “, part “ << part1.partnumber;
cout << “, costs $” << part1.cost << endl;
return 0; }
The program’s output looks like this:
1 - 49  Model 6244, part 373, costs $217.55
Manipulators
 Manipulators are operators used in C++ for formatting
output.
 The data is manipulated by the programmer’s choice of

display.
 There are numerous manipulators available in C++.

 Some of the more commonly used manipulators are:

 endl Manipulator
 setw Manipulator
 setfill Manipulator
 setprecision manipulator
1 - 50 50
endl Manipulator
 This manipulator has the same functionality as the ‘\n’
newline character
 Example:

cout<<“C++”<<endl;
cout<<“Training”;
 Output:

C++
Training

1 - 51 51
setw Manipulator

 This manipulator sets the minimum field width on output.


 The syntax is: setw(x)

 setw causes the number or string that follows it to be printed

within a field of x characters wide


 The header file that must be included while using setw

manipulator is # include<iomanip>
 Example: cout<<setw(8)<<“training”<<endl;

cout<<setw(16)<<“training”;
 Output:

training
training

1 - 52 3/15/2018 52
setfill Manipulator

 setfill is used after setw manipulator.


 If a value does not entirely fill a field, the character

specified in the setfill argument of the manipulator is


used for filling the fields.
 Example:

cout<<setw(8)<<setfill(‘$’)<<“C++”;
 Output:

$$$$$C++

1 - 53 3/15/2018 53
setprecision Manipulator
 This is used with floating point  Example:
numbers. int x=0.1;
 It is used to set the number of digits
printed to the right of the decimal cout<<fixed<<setprecision(3)<<x<
point.
<endl;
 Used in two forms: fixed and
scientific.
cout<<scientific<<setprecision()<<
 The keyword fixed before the x<<endl;
setprecision manipulator prints the
floating point number in fixed  Output:
notation. 0.100
 The keyword scientific, before the 1.000e-001
setprecision manipulator, prints the
floating point number in scientific
notation.
1 - 54 3/15/2018 54
Exercises
1. write a c++ program that 2. write a c++ program that
gives the following output. gives the following output.
0 0 1
0 1 12
0 2 123
1 0
1 1 1234
1 2 12345
2 0
2 1
2 2
3 0
3 1
3 2
1 - 55 3/15/2018 55
Solution for ex1 & 2
1. 2.
for(int j = 0; j <= 3; j++) for(int i=1;i<=5;i++)
{ {
for(int k = 0; k <= 2; k++) for (int s=1; s<=i;s++)
{
cout<< j<< " " << k<< {
endl; cout<<s;
} }
} cout<<endl;
}

1 - 56 56
Home work
 Write a C++ program that allows the user to enter a number
and generates a table of the first 200 multiples of the given
number in a 10 columns by 20 rows format using for loops.

1 - 57 57
OO Concepts Summary
 Object-oriented programming combines data and behavior (or method). This is
called encapsulation.
 Data hiding is the ability of an object to hide data from other objects in the
program.
 Only an object’s methods should be able to directly manipulate its attributes.
 Other objects are allowed to manipulate an object’s attributes via the object’s
methods.
 This indirect access is known as a programming interface.

 Classes can also define class variables and class methods which are
attributes and methods associated with the class as a whole.
 Inheritance allows classes to “inherit” attributes and methods from their base
(parent) class. This provides a clean mechanism for code re-use and
extension.

1 - 58
OO Concepts Summary
 Object-oriented programming is centered on creating objects
rather than procedures/ functions.
 Objects are a melding of data and procedures that

manipulate that data.


 Data in an object are known as attributes.

 Procedures/functions in an object are known as methods.

1 - 59
References
1. Introduction to Object-Oriented Analysis and Object-
Oriented Design, Mitchel G. Fry, CSTA Spring
Conference
2. Basic Concept of Object Oriented and Procedure
Oriented Programming, Mala Dutta
3. Object Oriented Programming, UTM open
courseware

1 - 60

Das könnte Ihnen auch gefallen