SlideShare uma empresa Scribd logo
1 de 55
Introduction to Object Technology,
Introduction to C++ Programming
Lecture No 2
COMSATS Institute of Information & Technology
Reference Books:
Object Oriented Programming in C++, Robert Lafore
C++ How to Program, Deitel & Deitel
Object oriented programming, Ashok N. Kamthane

2

COMSATS Institute of Information Technology
Object Oriented Programming
High-level Languages
Common programming languages include …

C C++ Java Pascal Visual Basic FORTRAN
COBOL Lisp Scheme Ada
These high – level languages
Resemble human languages
Are designed to be easy to read and write
Use more complicated instructions than
the CPU can follow
Must be translated to zeros and ones for the CPU
to execute a program
3

COMSATS Institute of Information Technology
Object Oriented Programming
Low-level Languages
An 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
4

COMSATS Institute of Information Technology
Object Oriented Programming
5

COMSATS Institute of Information Technology
Object Oriented Programming
Compilers
Translate high-level language to

machine language
Source code
 the original program in a high level language

Object code
 the translated version in machine language

6

COMSATS Institute of Information Technology
Object Oriented Programming
Linkers
Some programs we use are already compiled
Their object code is available for us to use
For example: Input and output routines

A Linker combines
The object code for the programs we write

and
The object code for the pre-compiled routines
into
The machine language program the CPU can run

7

COMSATS Institute of Information Technology
Object Oriented Programming
Programming
and Problem Solving
Algorithm
A sequence of precise instructions which

leads to a solution
Program
An algorithm expressed in a language the computer

can understand

8

COMSATS Institute of Information Technology
Object Oriented Programming
Program Design
Programming is a creative process
No complete set of rules for creating a program

Program Design Process
Problem Solving Phase
 Result is an algorithm that solves the problem

Implementation Phase
 Result is the algorithm translated into a programming

language

9

COMSATS Institute of Information Technology
Object Oriented Programming
Problem Solving Phase
Be 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 implementation
Experience shows this saves time in getting your

program to run.
Test the algorithm for correctness

10

COMSATS Institute of Information Technology
Object Oriented Programming
Implementation Phase
Translate the algorithm into a programming

language

Easier as you gain experience with the language

Compile the source code
Locates errors in using the programming language
Run the program on sample data
Verify correctness of results
Results may require modification of

the algorithm and program

11

COMSATS Institute of Information Technology
Object Oriented Programming
12

COMSATS Institute of Information Technology
Object Oriented Programming
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.

13

COMSATS Institute of Information Technology
Object Oriented Programming
Problems with Structured Programming
• Functions have unrestricted access to global data
Function A:

Function B:

Function C:

local data

local data

local data

global data X

global data Y

• 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
14

COMSATS Institute of Information Technology
Object Oriented Programming

global data Z
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
COMSATS Institute of Information Technology
15
Object Oriented Programming
model real world objects but a unified view is needed
Object Oriented
Programming
Abbreviated OOP
Used for many modern programs
Program is viewed as interacting objects
Each object contains algorithms to describe its behavior
Program design phase involves designing objects and

their algorithms

16

COMSATS Institute of Information Technology
Object Oriented Programming
OOP Characteristics
Encapsulation
Information hiding
Objects contain their own data and algorithms
Inheritance
Writing reusable code
Objects can inherit characteristics from other objects
Polymorphism
A single name can have multiple meanings depending
on its context
17

COMSATS Institute of Information Technology
Object Oriented Programming
Object Oriented Approach
Object
functions

data

• 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
18

COMSATS Institute of Information Technology
Object Oriented Programming
Object Oriented Approach
• separation: objects interact with each other only via their membership functions
• separation helps to maintain the integrity of the entire
program

Object A
functions

Object C
functions

data
19

COMSATS Institute of Information Technology
Object Oriented Programming

data

Object B
functions

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

abstraction

attributes

software

{data, data,…}

entity

behavior
20

COMSATS Institute of Information Technology
Object Oriented Programming

{ method, method…}
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

visible

hidden
21

COMSATS Institute of Information Technology
Object Oriented Programming

interface

Implementation
Structure of an Object
Implementation

Interface

Object
method

method

code

code
data

method
method
22

code
code

COMSATS Institute of Information Technology
Object Oriented Programming
Examples of Objects

23

• 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
COMSATS Institute of Information Technology
• time
Object Oriented Programming
• complex numbers
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; }
}
24

COMSATS Institute of Information Technology
Object Oriented Programming
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;

25

COMSATS Institute of Information Technology
Object Oriented Programming
Instantiation of Objects
person
data: name, p_nummer, address, date of birth
methods: getage(), changeaddress(newaddress)

Class

person
data: Lena Brat, 761203-7111, Stureplan 4, female
person
data: Erik Olsson, 780605-4789, Hamngatan 3, male
person
data: Lars Backe, 671110-A562, Mälartorget 19, male
26

COMSATS Institute of Information Technology
Object Oriented Programming
Relationships among Objects
• Attribute:

27

One object uses as another object as an attribute,
namely as member data, for example a Person
contains an attribute Name. This type of relationship 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 through
associations. This type of relationship is also
called a uses relationship.
Example: The object Driver invokes
COMSATS Institute of Information Technology
the method Brake
Object Oriented Programming of the object BrakingSystem.
Relationships among Objects
• Aggregation:
Aggregation means that one object contains other
objects. Aggregation is also called part-of relationship.
Example: The class Adressbook contains many People
Objects.
• 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.
28

COMSATS Institute of Information Technology
Object Oriented Programming
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.

29

COMSATS Institute of Information Technology
Object Oriented Programming
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.

base class
Vehicle
wheels
engine
Car

30

wheels
sub-classes or
engine
COMSATS Institute of Information Technologyderived classes
trunk
trunk
Object Oriented Programming

Truck
wheels
engine
trailer
trailer
Inheritance
• 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.

base class
Vehicle
brake()
start_engine()
Car
brake()
start_engine()
open_door()
open_door()
31

COMSATS Institute of Information Technology
Object Oriented Programming

Truck
sub-classes or
derived classes

brake()
start_engine()
open_door()
pull_trailer()
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.
32

COMSATS Institute of Information Technology
Object Oriented Programming
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.

33

COMSATS Institute of Information Technology
Object Oriented Programming
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.
34

COMSATS Institute of Information Technology
Object Oriented Programming
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);
35

COMSATS Institute of Information Technology
Object Oriented Programming
C++ and C

36

• 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
Software Life Cycle
1.
2.
3.
4.
5.

37

Analysis and specification of the task
(problem definition)
Design of the software
(object and algorithm design)
Implementation (coding)
Maintenance and evolution of the system
Obsolescence

COMSATS Institute of Information Technology
Object Oriented Programming
C++ History
C developed by Dennis Ritchie at AT&T

Bell Labs in the 1970s.

Used to maintain UNIX systems
Many commercial applications written in c

C++ developed by Bjarne Stroustrup at AT&T

Bell Labs in the 1980s.

Overcame several shortcomings of C
Incorporated object oriented programming
C remains a subset of C++

38

COMSATS Institute of Information Technology
Object Oriented Programming
C++ Standard Library
C++ programs
Built from pieces called classes and functions

C++ standard library
Rich collections of existing classes and functions

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

39

COMSATS Institute of Information Technology
Object Oriented Programming
Basics of a Typical C++ Environment
C++ systems
Program-development environment
Language
C++ Standard Library

40

COMSATS Institute of Information Technology
Object Oriented Programming
Basics of a Typical C++ Environment
Editor

Phases of C++ Programs:
1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. Execute

Program is created in
the editor and stored
on disk.

Disk

Preprocessor

Disk

Preprocessor program
processes the code.

Compiler

Disk

Compiler creates
object code and stores
it on disk.

Linker

Disk

Loader

Disk

Primary
Memory

Linker links the object
code with the libraries,
creates a.out and
stores it on disk

Loader puts program
in memory.
.
.
.
.
.
.

Primary
Memory

CPU

41

COMSATS Institute of Information Technology
Object Oriented Programming

.
.
.
.
.
.

CPU takes each
instruction and
executes it, possibly
storing new data
values as the program
executes.
A Sample C++ Program
A simple C++ program begins this way

#include <iostream>
using namespace std;
int main()
{
Statements;
}

42

return 0;

COMSATS Institute of Information Technology
Object Oriented Programming
#include <iostream>
using namespace std;
int main()
{
cout << “Hello Worldn”;
return 0;
}

43

COMSATS Institute of Information Technology
Object Oriented Programming
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 integern"; // prompt
cin >> integer1;

// read an integer

cout << "Enter second integern"; // 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
}

44

COMSATS Institute of Information Technology
Object Oriented Programming
Variables
Location in memory where value can be stored
Common data types
 int - integer numbers
 char - characters
 double - floating point numbers
Declare variables with name and data type before use
int integer1;
int integer2;
int sum;
Can declare several variables of same type in one declaration
 Comma-separated list
int integer1, integer2, sum;
45

COMSATS Institute of Information Technology
Object Oriented Programming
Variables
Variable names
 Valid identifier
 Series of characters (letters, digits, underscores)
 Cannot begin with digit
 Case sensitive

46

COMSATS Institute of Information Technology
Object Oriented Programming
Input stream object
>> (stream extraction operator)
 Used with cin
 Waits for user to input value, then press Enter (Return) key
 Stores value in variable to right of operator
 Converts value to variable data type

 = (assignment operator)
 Assigns value to variable
 Binary operator (two operands)
 Example:

sum = variable1 + variable2;

47

COMSATS Institute of Information Technology
Object Oriented Programming
 Comments

Document programs
Improve program readability
Ignored by compiler
Single-line comment
 Begin with //

 Preprocessor directives

Processed by preprocessor before compiling
Begin with #

Include Directives

#include <iostream>

Tells compiler where to find information about items

used in the program
iostream is a library containing definitions of cin and cout
48

COMSATS Institute of Information Technology
Object Oriented Programming
 Standard output stream object

cout
“Connected” to screen
<<
 Stream insertion operator
 Value to right (right operand) inserted into output stream

 Namespace

Tells the compiler to use names in iostream in

a “standard” way
std:: specifies using name that belongs to “namespace” std
std:: removed through use of using statements
 Escape characters


Indicates “special” character output

49

COMSATS Institute of Information Technology
Object Oriented Programming
Running a C++ Program
C++ 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 code

into an executable program.

50

COMSATS Institute of Information Technology
Object Oriented Programming
51

COMSATS Institute of Information Technology
Object Oriented Programming
52

COMSATS Institute of Information Technology
Object Oriented Programming
1.4

Testing and Debugging
Bug
A mistake in a program

Debugging
Eliminating mistakes in programs
Term 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.”

53

COMSATS Institute of Information Technology
Object Oriented Programming
Program Errors
Syntax errors
Violation of the grammar rules of the language
Discovered by the compiler
 Error messages may not always show correct location of

errors

Run-time errors
Error conditions detected by the computer at run-time
Logic errors
Errors in the program’s algorithm
Most difficult to diagnose
Computer does not recognize an error
54

COMSATS Institute of Information Technology
Object Oriented Programming
Escape Sequence
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.

"

55

Description

Double quote. Used to print a double quote
character.

COMSATS Institute of Information Technology
Object Oriented Programming

Mais conteúdo relacionado

Mais procurados

Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-pythonAakashdata
 
System Programming- Unit I
System Programming- Unit ISystem Programming- Unit I
System Programming- Unit ISaranya1702
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingAmit Soni (CTFL)
 
Array of objects.pptx
Array of objects.pptxArray of objects.pptx
Array of objects.pptxRAGAVIC2
 
Lecture 01 introduction to compiler
Lecture 01 introduction to compilerLecture 01 introduction to compiler
Lecture 01 introduction to compilerIffat Anjum
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAMaulik Borsaniya
 
Software project management- Software Engineering
Software project management- Software EngineeringSoftware project management- Software Engineering
Software project management- Software EngineeringMuhammad Yousuf Abdul Qadir
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingMoutaz Haddara
 
Software Project Management( lecture 1)
Software Project Management( lecture 1)Software Project Management( lecture 1)
Software Project Management( lecture 1)Syed Muhammad Hammad
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in pythonLifna C.S
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++Muhammad Waqas
 
COMPILER DESIGN OPTIONS
COMPILER DESIGN OPTIONSCOMPILER DESIGN OPTIONS
COMPILER DESIGN OPTIONSsonalikharade3
 
PROLOG: Arithmetic Operations In Prolog
PROLOG: Arithmetic Operations In PrologPROLOG: Arithmetic Operations In Prolog
PROLOG: Arithmetic Operations In PrologDataminingTools Inc
 

Mais procurados (20)

Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-python
 
System Programming- Unit I
System Programming- Unit ISystem Programming- Unit I
System Programming- Unit I
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Array of objects.pptx
Array of objects.pptxArray of objects.pptx
Array of objects.pptx
 
Lecture 01 introduction to compiler
Lecture 01 introduction to compilerLecture 01 introduction to compiler
Lecture 01 introduction to compiler
 
Lexical analysis - Compiler Design
Lexical analysis - Compiler DesignLexical analysis - Compiler Design
Lexical analysis - Compiler Design
 
Java applet
Java appletJava applet
Java applet
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
 
Python training
Python trainingPython training
Python training
 
Software project management- Software Engineering
Software project management- Software EngineeringSoftware project management- Software Engineering
Software project management- Software Engineering
 
Object oriented concepts ppt
Object oriented concepts pptObject oriented concepts ppt
Object oriented concepts ppt
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented Programming
 
Role-of-lexical-analysis
Role-of-lexical-analysisRole-of-lexical-analysis
Role-of-lexical-analysis
 
Python Presentation
Python PresentationPython Presentation
Python Presentation
 
Software Project Management( lecture 1)
Software Project Management( lecture 1)Software Project Management( lecture 1)
Software Project Management( lecture 1)
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
COMPILER DESIGN OPTIONS
COMPILER DESIGN OPTIONSCOMPILER DESIGN OPTIONS
COMPILER DESIGN OPTIONS
 
PROLOG: Arithmetic Operations In Prolog
PROLOG: Arithmetic Operations In PrologPROLOG: Arithmetic Operations In Prolog
PROLOG: Arithmetic Operations In Prolog
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 

Semelhante a Oop lec 2(introduction to object oriented technology)

A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...
A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...
A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...VMware Tanzu
 
programacion orientado a abjetos poo
programacion orientado a abjetos pooprogramacion orientado a abjetos poo
programacion orientado a abjetos pooRasec De La Cruz
 
OOP Unit 1 - Foundation of Object- Oriented Programming
OOP Unit 1 - Foundation of Object- Oriented ProgrammingOOP Unit 1 - Foundation of Object- Oriented Programming
OOP Unit 1 - Foundation of Object- Oriented Programmingdkpawar
 
Unit 1 introduction to c++.pptx
Unit 1 introduction to c++.pptxUnit 1 introduction to c++.pptx
Unit 1 introduction to c++.pptxshashiden1
 
Principles of object oriented programing
Principles of object oriented programingPrinciples of object oriented programing
Principles of object oriented programingAhammed Alamin
 
Lecture-4: Introduction to Programming & Databases
Lecture-4: Introduction to Programming & DatabasesLecture-4: Introduction to Programming & Databases
Lecture-4: Introduction to Programming & DatabasesMubashir Ali
 
Need of OOPs and Programming,pop vs oop
Need of OOPs and Programming,pop vs oopNeed of OOPs and Programming,pop vs oop
Need of OOPs and Programming,pop vs oopJanani Selvaraj
 
Introduction to oop
Introduction to oop Introduction to oop
Introduction to oop Kumar
 

Semelhante a Oop lec 2(introduction to object oriented technology) (20)

C++
C++C++
C++
 
JAVA PROGRAMMINGD
JAVA PROGRAMMINGDJAVA PROGRAMMINGD
JAVA PROGRAMMINGD
 
OOP-1.pptx
OOP-1.pptxOOP-1.pptx
OOP-1.pptx
 
Part 1
Part 1Part 1
Part 1
 
A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...
A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...
A Modern Interface for Data Science on Postgres/Greenplum - Greenplum Summit ...
 
programacion orientado a abjetos poo
programacion orientado a abjetos pooprogramacion orientado a abjetos poo
programacion orientado a abjetos poo
 
JAVA PROGRAMMING
JAVA PROGRAMMING JAVA PROGRAMMING
JAVA PROGRAMMING
 
Birasa 1
Birasa 1Birasa 1
Birasa 1
 
OOP Unit 1 - Foundation of Object- Oriented Programming
OOP Unit 1 - Foundation of Object- Oriented ProgrammingOOP Unit 1 - Foundation of Object- Oriented Programming
OOP Unit 1 - Foundation of Object- Oriented Programming
 
Unit 1 introduction to c++.pptx
Unit 1 introduction to c++.pptxUnit 1 introduction to c++.pptx
Unit 1 introduction to c++.pptx
 
Principles of object oriented programing
Principles of object oriented programingPrinciples of object oriented programing
Principles of object oriented programing
 
1 puc programming using c++
1 puc programming using c++1 puc programming using c++
1 puc programming using c++
 
Lecture-4: Introduction to Programming & Databases
Lecture-4: Introduction to Programming & DatabasesLecture-4: Introduction to Programming & Databases
Lecture-4: Introduction to Programming & Databases
 
why to do BCA course?
why to do BCA course?why to do BCA course?
why to do BCA course?
 
Need of OOPs and Programming,pop vs oop
Need of OOPs and Programming,pop vs oopNeed of OOPs and Programming,pop vs oop
Need of OOPs and Programming,pop vs oop
 
Introduction to oop
Introduction to oop Introduction to oop
Introduction to oop
 
OODPunit1.pdf
OODPunit1.pdfOODPunit1.pdf
OODPunit1.pdf
 
Oop obj c
Oop obj cOop obj c
Oop obj c
 
OOPS_Unit_1
OOPS_Unit_1OOPS_Unit_1
OOPS_Unit_1
 
Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1
 

Mais de Asfand Hassan

Pak US relation 130411005046-phpapp01
Pak US relation 130411005046-phpapp01Pak US relation 130411005046-phpapp01
Pak US relation 130411005046-phpapp01Asfand Hassan
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Asfand Hassan
 
Oop lec 3(structures)
Oop lec 3(structures)Oop lec 3(structures)
Oop lec 3(structures)Asfand Hassan
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Asfand Hassan
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Asfand Hassan
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Asfand Hassan
 

Mais de Asfand Hassan (13)

Pak US relation 130411005046-phpapp01
Pak US relation 130411005046-phpapp01Pak US relation 130411005046-phpapp01
Pak US relation 130411005046-phpapp01
 
Chap5java5th
Chap5java5thChap5java5th
Chap5java5th
 
Chap6java5th
Chap6java5thChap6java5th
Chap6java5th
 
Chap4java5th
Chap4java5thChap4java5th
Chap4java5th
 
Chap3java5th
Chap3java5thChap3java5th
Chap3java5th
 
Chap2java5th
Chap2java5thChap2java5th
Chap2java5th
 
Chap1java5th
Chap1java5thChap1java5th
Chap1java5th
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]
 
Oop lec 3(structures)
Oop lec 3(structures)Oop lec 3(structures)
Oop lec 3(structures)
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)
 
Oop lec 1
Oop lec 1Oop lec 1
Oop lec 1
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)
 

Último

ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 

Último (20)

Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 

Oop lec 2(introduction to object oriented technology)

  • 1. Introduction to Object Technology, Introduction to C++ Programming Lecture No 2 COMSATS Institute of Information & Technology
  • 2. Reference Books: Object Oriented Programming in C++, Robert Lafore C++ How to Program, Deitel & Deitel Object oriented programming, Ashok N. Kamthane 2 COMSATS Institute of Information Technology Object Oriented Programming
  • 3. High-level Languages Common programming languages include … C C++ Java Pascal Visual Basic FORTRAN COBOL Lisp Scheme Ada These high – level languages Resemble human languages Are designed to be easy to read and write Use more complicated instructions than the CPU can follow Must be translated to zeros and ones for the CPU to execute a program 3 COMSATS Institute of Information Technology Object Oriented Programming
  • 4. Low-level Languages An 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 4 COMSATS Institute of Information Technology Object Oriented Programming
  • 5. 5 COMSATS Institute of Information Technology Object Oriented Programming
  • 6. Compilers Translate high-level language to machine language Source code  the original program in a high level language Object code  the translated version in machine language 6 COMSATS Institute of Information Technology Object Oriented Programming
  • 7. Linkers Some programs we use are already compiled Their object code is available for us to use For example: Input and output routines A Linker combines The object code for the programs we write and The object code for the pre-compiled routines into The machine language program the CPU can run 7 COMSATS Institute of Information Technology Object Oriented Programming
  • 8. Programming and Problem Solving Algorithm A sequence of precise instructions which leads to a solution Program An algorithm expressed in a language the computer can understand 8 COMSATS Institute of Information Technology Object Oriented Programming
  • 9. Program Design Programming is a creative process No complete set of rules for creating a program Program Design Process Problem Solving Phase  Result is an algorithm that solves the problem Implementation Phase  Result is the algorithm translated into a programming language 9 COMSATS Institute of Information Technology Object Oriented Programming
  • 10. Problem Solving Phase Be 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 implementation Experience shows this saves time in getting your program to run. Test the algorithm for correctness 10 COMSATS Institute of Information Technology Object Oriented Programming
  • 11. Implementation Phase Translate the algorithm into a programming language Easier as you gain experience with the language Compile the source code Locates errors in using the programming language Run the program on sample data Verify correctness of results Results may require modification of the algorithm and program 11 COMSATS Institute of Information Technology Object Oriented Programming
  • 12. 12 COMSATS Institute of Information Technology Object Oriented Programming
  • 13. 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. 13 COMSATS Institute of Information Technology Object Oriented Programming
  • 14. Problems with Structured Programming • Functions have unrestricted access to global data Function A: Function B: Function C: local data local data local data global data X global data Y • 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 14 COMSATS Institute of Information Technology Object Oriented Programming global data Z
  • 15. 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 COMSATS Institute of Information Technology 15 Object Oriented Programming model real world objects but a unified view is needed
  • 16. Object Oriented Programming Abbreviated OOP Used for many modern programs Program is viewed as interacting objects Each object contains algorithms to describe its behavior Program design phase involves designing objects and their algorithms 16 COMSATS Institute of Information Technology Object Oriented Programming
  • 17. OOP Characteristics Encapsulation Information hiding Objects contain their own data and algorithms Inheritance Writing reusable code Objects can inherit characteristics from other objects Polymorphism A single name can have multiple meanings depending on its context 17 COMSATS Institute of Information Technology Object Oriented Programming
  • 18. Object Oriented Approach Object functions data • 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 18 COMSATS Institute of Information Technology Object Oriented Programming
  • 19. Object Oriented Approach • separation: objects interact with each other only via their membership functions • separation helps to maintain the integrity of the entire program Object A functions Object C functions data 19 COMSATS Institute of Information Technology Object Oriented Programming data Object B functions data
  • 20. Abstraction • An abstraction is a named collection of attributes and behavior relevant to model a given entity for some particular purpose real-world abstraction attributes software {data, data,…} entity behavior 20 COMSATS Institute of Information Technology Object Oriented Programming { method, method…}
  • 21. 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 visible hidden 21 COMSATS Institute of Information Technology Object Oriented Programming interface Implementation
  • 22. Structure of an Object Implementation Interface Object method method code code data method method 22 code code COMSATS Institute of Information Technology Object Oriented Programming
  • 23. Examples of Objects 23 • 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 COMSATS Institute of Information Technology • time Object Oriented Programming • complex numbers
  • 24. 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; } } 24 COMSATS Institute of Information Technology Object Oriented Programming
  • 25. 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; 25 COMSATS Institute of Information Technology Object Oriented Programming
  • 26. Instantiation of Objects person data: name, p_nummer, address, date of birth methods: getage(), changeaddress(newaddress) Class person data: Lena Brat, 761203-7111, Stureplan 4, female person data: Erik Olsson, 780605-4789, Hamngatan 3, male person data: Lars Backe, 671110-A562, Mälartorget 19, male 26 COMSATS Institute of Information Technology Object Oriented Programming
  • 27. Relationships among Objects • Attribute: 27 One object uses as another object as an attribute, namely as member data, for example a Person contains an attribute Name. This type of relationship 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 through associations. This type of relationship is also called a uses relationship. Example: The object Driver invokes COMSATS Institute of Information Technology the method Brake Object Oriented Programming of the object BrakingSystem.
  • 28. Relationships among Objects • Aggregation: Aggregation means that one object contains other objects. Aggregation is also called part-of relationship. Example: The class Adressbook contains many People Objects. • 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. 28 COMSATS Institute of Information Technology Object Oriented Programming
  • 29. 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. 29 COMSATS Institute of Information Technology Object Oriented Programming
  • 30. 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. base class Vehicle wheels engine Car 30 wheels sub-classes or engine COMSATS Institute of Information Technologyderived classes trunk trunk Object Oriented Programming Truck wheels engine trailer trailer
  • 31. Inheritance • 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. base class Vehicle brake() start_engine() Car brake() start_engine() open_door() open_door() 31 COMSATS Institute of Information Technology Object Oriented Programming Truck sub-classes or derived classes brake() start_engine() open_door() pull_trailer()
  • 32. 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. 32 COMSATS Institute of Information Technology Object Oriented Programming
  • 33. 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. 33 COMSATS Institute of Information Technology Object Oriented Programming
  • 34. 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. 34 COMSATS Institute of Information Technology Object Oriented Programming
  • 35. 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); 35 COMSATS Institute of Information Technology Object Oriented Programming
  • 36. C++ and C 36 • 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
  • 37. Software Life Cycle 1. 2. 3. 4. 5. 37 Analysis and specification of the task (problem definition) Design of the software (object and algorithm design) Implementation (coding) Maintenance and evolution of the system Obsolescence COMSATS Institute of Information Technology Object Oriented Programming
  • 38. C++ History C developed by Dennis Ritchie at AT&T Bell Labs in the 1970s. Used to maintain UNIX systems Many commercial applications written in c C++ developed by Bjarne Stroustrup at AT&T Bell Labs in the 1980s. Overcame several shortcomings of C Incorporated object oriented programming C remains a subset of C++ 38 COMSATS Institute of Information Technology Object Oriented Programming
  • 39. C++ Standard Library C++ programs Built from pieces called classes and functions C++ standard library Rich collections of existing classes and functions “Building block approach” to creating programs “Software reuse” 39 COMSATS Institute of Information Technology Object Oriented Programming
  • 40. Basics of a Typical C++ Environment C++ systems Program-development environment Language C++ Standard Library 40 COMSATS Institute of Information Technology Object Oriented Programming
  • 41. Basics of a Typical C++ Environment Editor Phases of C++ Programs: 1. Edit 2. Preprocess 3. Compile 4. Link 5. Load 6. Execute Program is created in the editor and stored on disk. Disk Preprocessor Disk Preprocessor program processes the code. Compiler Disk Compiler creates object code and stores it on disk. Linker Disk Loader Disk Primary Memory Linker links the object code with the libraries, creates a.out and stores it on disk Loader puts program in memory. . . . . . . Primary Memory CPU 41 COMSATS Institute of Information Technology Object Oriented Programming . . . . . . CPU takes each instruction and executes it, possibly storing new data values as the program executes.
  • 42. A Sample C++ Program A simple C++ program begins this way #include <iostream> using namespace std; int main() { Statements; } 42 return 0; COMSATS Institute of Information Technology Object Oriented Programming
  • 43. #include <iostream> using namespace std; int main() { cout << “Hello Worldn”; return 0; } 43 COMSATS Institute of Information Technology Object Oriented Programming
  • 44. 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 integern"; // prompt cin >> integer1; // read an integer cout << "Enter second integern"; // 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 } 44 COMSATS Institute of Information Technology Object Oriented Programming
  • 45. Variables Location in memory where value can be stored Common data types  int - integer numbers  char - characters  double - floating point numbers Declare variables with name and data type before use int integer1; int integer2; int sum; Can declare several variables of same type in one declaration  Comma-separated list int integer1, integer2, sum; 45 COMSATS Institute of Information Technology Object Oriented Programming
  • 46. Variables Variable names  Valid identifier  Series of characters (letters, digits, underscores)  Cannot begin with digit  Case sensitive 46 COMSATS Institute of Information Technology Object Oriented Programming
  • 47. Input stream object >> (stream extraction operator)  Used with cin  Waits for user to input value, then press Enter (Return) key  Stores value in variable to right of operator  Converts value to variable data type  = (assignment operator)  Assigns value to variable  Binary operator (two operands)  Example: sum = variable1 + variable2; 47 COMSATS Institute of Information Technology Object Oriented Programming
  • 48.  Comments Document programs Improve program readability Ignored by compiler Single-line comment  Begin with //  Preprocessor directives Processed by preprocessor before compiling Begin with # Include Directives #include <iostream> Tells compiler where to find information about items used in the program iostream is a library containing definitions of cin and cout 48 COMSATS Institute of Information Technology Object Oriented Programming
  • 49.  Standard output stream object cout “Connected” to screen <<  Stream insertion operator  Value to right (right operand) inserted into output stream  Namespace Tells the compiler to use names in iostream in a “standard” way std:: specifies using name that belongs to “namespace” std std:: removed through use of using statements  Escape characters  Indicates “special” character output 49 COMSATS Institute of Information Technology Object Oriented Programming
  • 50. Running a C++ Program C++ 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 code into an executable program. 50 COMSATS Institute of Information Technology Object Oriented Programming
  • 51. 51 COMSATS Institute of Information Technology Object Oriented Programming
  • 52. 52 COMSATS Institute of Information Technology Object Oriented Programming
  • 53. 1.4 Testing and Debugging Bug A mistake in a program Debugging Eliminating mistakes in programs Term 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.” 53 COMSATS Institute of Information Technology Object Oriented Programming
  • 54. Program Errors Syntax errors Violation of the grammar rules of the language Discovered by the compiler  Error messages may not always show correct location of errors Run-time errors Error conditions detected by the computer at run-time Logic errors Errors in the program’s algorithm Most difficult to diagnose Computer does not recognize an error 54 COMSATS Institute of Information Technology Object Oriented Programming
  • 55. Escape Sequence 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. " 55 Description Double quote. Used to print a double quote character. COMSATS Institute of Information Technology Object Oriented Programming