Oop lec 2(introduction to object oriented technology)

Preview:

DESCRIPTION

 

Citation preview

Lecture No 2COMSATS Institute of Information &

Technology

Introduction to Object Technology, Introduction to C+

+ Programming

COMSATS Institute of Information Technology Object Oriented Programming

2

Reference Books:Object Oriented Programming in C++, Robert

LaforeC++ How to Program, Deitel & DeitelObject oriented programming, Ashok N.

Kamthane

High-level LanguagesCommon programming languages include …

C C++ Java Pascal Visual Basic FORTRAN COBOL Lisp Scheme Ada

These high – level languages Resemble human languagesAre designed to be easy to read and writeUse more complicated instructions than

the CPU can followMust be translated to zeros and ones for the CPU

to execute a program

COMSATS Institute of Information Technology Object Oriented Programming

3

Low-level LanguagesAn assembly language command such as

ADD X Y Z

might mean add the values found at x and y in memory, and store the result in location z.

Assembly language must be translated to machine language (zeros and ones) 0110 1001 1010 1011

The CPU can follow machine language

COMSATS Institute of Information Technology Object Oriented Programming

4

COMSATS Institute of Information Technology Object Oriented Programming

5

CompilersTranslate high-level language to

machine language

Source code the original program in a high level language

Object code the translated version in machine language

COMSATS Institute of Information Technology Object Oriented Programming

6

LinkersSome programs we use are already

compiledTheir object code is available for us to useFor example: Input and output routines

A Linker combinesThe object code for the programs we write

andThe object code for the pre-compiled routines

intoThe machine language program the CPU can

run

COMSATS Institute of Information Technology Object Oriented Programming

7

Programming and Problem Solving

AlgorithmA sequence of precise instructions which

leads to a solution

ProgramAn algorithm expressed in a language the

computercan understand

COMSATS Institute of Information Technology Object Oriented Programming

8

Program DesignProgramming is a creative process

No complete set of rules for creating a program

Program Design ProcessProblem Solving Phase

Result is an algorithm that solves the problemImplementation Phase

Result is the algorithm translated into a programminglanguage

COMSATS Institute of Information Technology Object Oriented Programming

9

Problem Solving PhaseBe certain the task is completely specified

What is the input? What information is in the output? How is the output organized?

Develop the algorithm before implementationExperience shows this saves time in getting

yourprogram to run.

Test the algorithm for correctness

COMSATS Institute of Information Technology Object Oriented Programming

10

Implementation PhaseTranslate the algorithm into a programming

languageEasier as you gain experience with the language

Compile the source codeLocates errors in using the programming

language

Run the program on sample dataVerify correctness of results

Results may require modification of the algorithm and programCOMSATS Institute of Information

Technology Object Oriented Programming

11

COMSATS Institute of Information Technology Object Oriented Programming

12

Procedural Languages

• Examples of procedural languages: C, Pascal, Fortran• A program in a procedural language is basically a list of instructions• As programs become larger they are usually broken down into smaller units, such as functions, procedures, subroutines• Functions can be grouped together into modules according to their functionality, objectives and tasks.• Structured programming is a programming paradigm that to a large extent relies on the idea of dividing a program into functions and modules.

COMSATS Institute of Information Technology Object Oriented Programming

13

Problems with Structured Programming

• Functions have unrestricted access to global data

global data Y

Function A:

local data

Function B:

local data

Function C:

local data

• Large number of potential connections between functions and data (everything is related to everything, no clear boundaries)

• makes it difficult to conceptualize program structure• makes it difficult to modify and maintain the program e.g. : it is difficult to tell which functions access the data

global data X global data Z

COMSATS Institute of Information Technology Object Oriented Programming

14

Problems with Structured Programming

• data and function are considered as two separate entities• makes it difficult to model things in the real world• complex real world objects have both attributes and behaviours • attributes

• people: name, date of birth, eye color, job title• cars: horse power, number of doors, color

• behaviours• people: ask a person to bring you a beer• cars: apply the brakes, turn on the engine

• attributes and behaviors alone are sufficient to realistically model real world objects but a unified view is needed

COMSATS Institute of Information Technology Object Oriented Programming

15

Object Oriented ProgrammingAbbreviated OOP

Used for many modern programs

Program is viewed as interacting objectsEach object contains algorithms to describe

its behaviorProgram design phase involves designing

objects andtheir algorithms

COMSATS Institute of Information Technology Object Oriented Programming

16

OOP CharacteristicsEncapsulation

Information hidingObjects contain their own data and algorithms

InheritanceWriting reusable codeObjects can inherit characteristics from other

objects

PolymorphismA single name can have multiple meanings

depending on its context

COMSATS Institute of Information Technology Object Oriented Programming

17

Object Oriented Approach

Object

data

functions

• Encapsulation: integrate data and functions into one object• Data hiding : data is hidden to the outside world and can only be accessed via the functions • In C++ functions are called membership functions in other languages they are called methods• Data items are called attributes or instance variables COMSATS Institute of Information

Technology Object Oriented Programming

18

Object Oriented Approach

Object A

data

functions

Object C

data

functions

Object B

data

functions

• separation: objects interact with each other only via their membership functions• separation helps to maintain the integrity of the entire program

COMSATS Institute of Information Technology Object Oriented Programming

19

Abstraction• An abstraction is a named collection of attributes and behavior relevant to model a given entity for some particular purpose

entityattributes

behavior

{data, data,…}

{ method, method…}

real-world abstraction software

COMSATS Institute of Information Technology Object Oriented Programming

20

Separation• independent specification of a visible interface and a hidden implementation• interface is some kind of contract between the object and the user of this object or module• separation is not restricted to object-oriented programming for example header files in standard C can be regarded as interfaces

Imple-mentation

interfacevisible

hiddenCOMSATS Institute of Information Technology Object Oriented Programming

21

Structure of an Object

Object

data

method code

method code

method code

method code

Interface Implementation

COMSATS Institute of Information Technology Object Oriented Programming

22

Examples of Objects• physcial objects

• vehicles in a traffic-flow simulation• electrical components in a circuit-design program

• elements of a computer user environment• menus• graphic objects

• data-storage constructs• arrays• linked lists

• human entities• employees• students

• collections of data• an inventory• an address book

• user defined data types• time• complex numbers

COMSATS Institute of Information Technology Object Oriented Programming

23

Example of a Class in C++

class someobject //declares a class { private: int somedata; //class data public: void setdata(int d) //membership function to set data { somedata=d; } int getdata() //membership function to get data { return somedata; } }

COMSATS Institute of Information Technology Object Oriented Programming

24

Classes versus Objects• A class is a prototype specification from which one can generate a number of similar objects • A class can be considered as an object factory.• An object is said to be a member or instance of a class• A class can be considered as a more complex data structure than an ordinary built-in data type• Standard C already knows the struct command for user defined data types: struct complex { double re; double im; }; complex x;

COMSATS Institute of Information Technology Object Oriented Programming

25

Instantiation of Objects

person data: name, p_nummer, address, date of birth methods: getage(), changeaddress(newaddress)

Class

person data: Erik Olsson, 780605-4789, Hamngatan 3, male

person data: Lena Brat, 761203-7111, Stureplan 4, female

person data: Lars Backe, 671110-A562, Mälartorget 19, male

COMSATS Institute of Information Technology Object Oriented Programming

26

Relationships among Objects

• Attribute: One object uses as another object as an attribute, namely as member data, for example a Person contains an attribute Name. This type of relation- ship is also called a weak association or has-a relationship. Example: A Person has a Name

• Association:One object uses another to help it carry out a task.Classes that collaborate are usually related throughassociations. This type of relationship is alsocalled a uses relationship.Example: The object Driver invokesthe method Brake of the object BrakingSystem.

COMSATS Institute of Information Technology Object Oriented Programming

27

Relationships among Objects• Aggregation:

Aggregation means that one object contains otherobjects. Aggregation is also called part-of relationship.Example: The class Adressbook contains many PeopleObjects.

• Composition: Composition is building objects from parts. It is a stronger type of aggregation in which the parts are necessary to the whole, namely they are permanently bound to the object and do not exist outside the object. A class Processor contains a CPU, Memory and I/O-Ports.

COMSATS Institute of Information Technology Object Oriented Programming

28

Relationships among Objects

• Generalization Generalization is a relationship defined at the class level not the object level, which means that all objects of this class must obey the relationship. This is type of relationship is also called a is-a-kind-of relationship. Generalization in object oriented languages is realized by means of inheritance. Example: A car is a kind of vehicle.

COMSATS Institute of Information Technology Object Oriented Programming

29

Inheritance• In our daily lives we use the concept of classes divided into subclasses, for example vehicles are divided into cars, trucks, buses and motor cycles.• The principle in this sort of division is that each sub-class shares some common features with the base class from which it is derived, but also has its own particular features.

Vehicle

wheelsengine

Car

wheelsenginetrunk

Truck

wheelsenginetrailertrunk trailer

base class

sub-classes orderived classes

COMSATS Institute of Information Technology Object Oriented Programming

30

Truck

Inheritance

Vehicle

brake()start_engine()

Car

brake()start_engine()open_door()pull_trailer()

base class

sub-classes orderived classes

• A sub-class also shares common methods with its super-class but can add its own methods or overwrite the methods of its super-class.

brake()start_engine()open_door()open_door()COMSATS Institute of Information Technology Object Oriented Programming

31

Inheritance

Terminology: • Car is a sub-class (or derived class) of Vehicle • Car inherits from Vehicle• Car is a specialization of Vehicle• Vehicle is a super-class (or base class) of Car• Vehicle is a generalization of Car

• In C++ an object of a sub-class is substitutable for an object of the super-class, in other words an object of class Car can be used whenever an object of class Vehicle is required.

COMSATS Institute of Information Technology Object Oriented Programming

32

Reusability

• Reusability means that a class that has been designed, created and debugged once can be distributed to other programmers for use in their own programs.• Similar to the idea of a library of functions in a procedural language.• The concept of inheritance provides an important extension to the idea of reusability, as it allows a programmer to take an existing class without modifying it and adding additional features and functionality. This is done by inheriting a new sub-class from the exisiting base class.

COMSATS Institute of Information Technology Object Oriented Programming

33

Polymorphism & Overloading

• Polymorphism : using functions and operators in different ways, depending on what they are operating on.• Polymorphism allows it to manipulate objects without knowing their exact type but only their common property. for example, the classes Triangle and Circle both have their own (polymorphic) version of the method Draw, but a graphic routine that draws graphical elements does not have to know which object it manipulates.• Overloading: an existing operator, such as + or = is given the capability to operate on a new data type, for example define the operator + for the class Complex such that it realizes the addition of two complex numbers.COMSATS Institute of Information

Technology Object Oriented Programming

34

Polymorphism

• polymorphism means ”having many shapes”• in C++ it refers to a situation in which an object could have any of several types• a polymorphic variable can refer to objects of different classes, for example a graphic object can be either a circle or a triangle• a polymorphic function or operator can take arguments of different types• example: int max(int a, int b); double max(double a, double b);

COMSATS Institute of Information Technology Object Oriented Programming

35

C++ and C

• C++ is derived from the language C• C++ is a superset of C, that means almost every correct statement in C is also correct in C++• The most important elements added to C are concerned with classes, objects and object-oriented programming• New features of C++

• improved approach to input/output• standard template library (STL) container classes for vectors, lists, maps, etc.• reference type replaces pointers• const variables replaces #define statements• string data type replaces C-style strings char[]• new comment style augments C-style comments /* */COMSATS Institute of Information

Technology Object Oriented Programming

36

Software Life Cycle1. Analysis and specification of the task

(problem definition)2. Design of the software

(object and algorithm design)3. Implementation (coding)4. Maintenance and evolution of the

system5. Obsolescence

COMSATS Institute of Information Technology Object Oriented Programming

37

C++ HistoryC developed by Dennis Ritchie at AT&T

Bell Labs in the 1970s.Used to maintain UNIX systemsMany commercial applications written in c

C++ developed by Bjarne Stroustrup at AT&TBell Labs in the 1980s.Overcame several shortcomings of CIncorporated object oriented programmingC remains a subset of C++

COMSATS Institute of Information Technology Object Oriented Programming

38

C++ Standard LibraryC++ programs

Built from pieces called classes and functionsC++ standard library

Rich collections of existing classes and functions

“Building block approach” to creating programs“Software reuse”

COMSATS Institute of Information Technology Object Oriented Programming

39

Basics of a Typical C++ EnvironmentC++ systems

Program-development environmentLanguageC++ Standard Library

COMSATS Institute of Information Technology Object Oriented Programming

40

Basics of a Typical C++ Environment

Phases of C++ Programs:1. Edit2. Preprocess3. Compile4. Link5. Load6. Execute

Loader

PrimaryMemory

Program is created inthe editor and storedon disk.

Preprocessor programprocesses the code.

Loader puts programin memory.

CPU takes eachinstruction andexecutes it, possiblystoring new datavalues as the programexecutes.

CompilerCompiler createsobject code and storesit on disk.

Linker links the objectcode with the libraries,creates a.out andstores it on disk

Editor

Preprocessor

Linker

 CPU

PrimaryMemory

.

.

.

.

.

.

.

.

.

.

.

.

Disk

Disk

Disk

Disk

Disk

COMSATS Institute of Information Technology Object Oriented Programming

41

A Sample C++ ProgramA simple C++ program begins this way

#include <iostream>using namespace std;

int main(){ Statements;

return 0;}

COMSATS Institute of Information Technology Object Oriented Programming

42

#include <iostream>using namespace std;

int main(){ cout << “Hello World\n”;

return 0;}

COMSATS Institute of Information Technology Object Oriented Programming

43

Example: Adding Two Integers #include <iostream>

using namespace std;

// function main begins program execution

int main()

{

int integer1; // first number to be input by user

int integer2; // second number to be input by user

int sum; // variable in which sum will be stored

cout << "Enter first integer\n"; // prompt

cin >> integer1; // read an integer

cout << "Enter second integer\n"; // prompt

cin >> integer2; // read an integer

sum = integer1 + integer2; // assign result to sum

cout << "Sum is " << sum << endl; // print sum

return 0; // indicate that program ended successfully

}

COMSATS Institute of Information Technology Object Oriented Programming

44

Variables Location in memory where value can be storedCommon data types

int - integer numberschar - charactersdouble - floating point numbers

Declare variables with name and data type before useint integer1;int integer2;int sum;

Can declare several variables of same type in one declarationComma-separated listint integer1, integer2, sum;

COMSATS Institute of Information Technology Object Oriented Programming

45

VariablesVariable names

Valid identifierSeries of characters (letters, digits, underscores)Cannot begin with digitCase sensitive

COMSATS Institute of Information Technology Object Oriented Programming

46

Input stream object>> (stream extraction operator)

Used with cinWaits for user to input value, then press Enter

(Return) keyStores value in variable to right of operator

Converts value to variable data type= (assignment operator)

Assigns value to variableBinary operator (two operands)Example:

sum = variable1 + variable2;

COMSATS Institute of Information Technology Object Oriented Programming

47

CommentsDocument programsImprove program readabilityIgnored by compilerSingle-line comment

Begin with //Preprocessor directives

Processed by preprocessor before compilingBegin with #

Include Directives #include <iostream>Tells compiler where to find information about items

used in the programiostream is a library containing definitions of cin and

coutCOMSATS Institute of Information Technology Object Oriented Programming

48

Standard output stream objectcout“Connected” to screen<<

Stream insertion operator Value to right (right operand) inserted into output stream

NamespaceTells the compiler to use names in iostream in

a “standard” waystd:: specifies using name that belongs to

“namespace” stdstd:: removed through use of using statements

Escape characters\Indicates “special” character output

COMSATS Institute of Information Technology Object Oriented Programming

49

Running a C++ ProgramC++ source code is written with a text

editor

The compiler on your system converts source code to object code.

The linker combines all the object codeinto an executable program.

COMSATS Institute of Information Technology Object Oriented Programming

50

COMSATS Institute of Information Technology Object Oriented Programming

51

COMSATS Institute of Information Technology Object Oriented Programming

52

Testing and DebuggingBug

A mistake in a programDebugging

Eliminating mistakes in programsTerm used when a moth caused a failed relay

on the Harvard Mark 1 computer. Grace Hopper and other programmers taped the moth in logbook stating: “First actual case of a bug being found.”

1.4

COMSATS Institute of Information Technology Object Oriented Programming

53

Program ErrorsSyntax errors

Violation of the grammar rules of the languageDiscovered by the compiler

Error messages may not always show correct location of

errorsRun-time errors

Error conditions detected by the computer at run-time

Logic errorsErrors in the program’s algorithmMost difficult to diagnoseComputer does not recognize an error

COMSATS Institute of Information Technology Object Oriented Programming

54

Escape Sequence Description

\n Newline. Position the screen cursor to the beginning of the next line.

\t Horizontal tab. Move the screen cursor to the next tab stop.

\r Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line.

\a Alert. Sound the system bell.

\\ Backslash. Used to print a backslash character.

\" Double quote. Used to print a double quote character.

COMSATS Institute of Information Technology Object Oriented Programming

55

Recommended