Beruflich Dokumente
Kultur Dokumente
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.
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
1-9
Software Objects
Writing software often involves creating a computational model
of real-world objects and processes.
behaviors.
Your best bet is to think in terms as close as possible to the
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)
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
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
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
Methods
accountNumber()
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.
private.
It is necessary to instantiate (create an instance of) a class to
1 - 19
Class Methods and Class Variables
In addition to instance methods and instance variables, classes
can also define class methods and class variables.
1 - 20
Class Variables
A class variable defines an attribute of an entire class.
In contrast, an instance variable defines an attribute of a
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).
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
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
rate() withdraw()
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
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:
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.
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
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
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,
used.
Java lacks certain features—such as pointers, templates,
1 - 34
Similarities between C and C++
same built-in data types
same compiler preprocessor
1 - 35
Differences C vs C++
C Programming C++ Programming
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,
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
input/output operations
iostream contains code to define cout and cin identifiers,
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
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, <<
The << operator inserts the data that follows it into the
1 - 43
Standard Input (cin)
The standard input device is usually the keyboard.
Handling the standard input in C++ is done by
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
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:
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
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++.
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
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
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
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