OOPs Slides by Harish Kumar

146
Queries: [email protected] Computer Programming Harish Kumar, UIET, Panjab University, Chandigarh

Transcript of OOPs Slides by Harish Kumar

Page 1: OOPs Slides by Harish Kumar

Queries: [email protected]

Computer Programming

Harish Kumar, UIET, Panjab University, Chandigarh

Page 2: OOPs Slides by Harish Kumar

Queries: [email protected] 2

Session I

Page 3: OOPs Slides by Harish Kumar

Queries: [email protected] 3

Computer Fundamentals

Page 4: OOPs Slides by Harish Kumar

Queries: [email protected] 4

• A computer program is…– A set of instructions for a computer to follow

• Computer software is …– The collection of programs used by a computer

• Includes:

– Various System Software like Editors, Translators, Operating Systems etc.

– Various Application Software like Word Processor, Simulation Software etc.

Software

Page 5: OOPs Slides by Harish Kumar

Queries: [email protected] 5

Page 6: OOPs Slides by Harish Kumar

Queries: [email protected] 6

Computer Organization

– Five main components

• Input devices --------- Allows communication to the computer

• Output devices ------- Allows communication to the user

• Processor (CPU) ----- Executing Instructions (Pentium, Sparc, PowerPc, K6)

• Main memory -------- Memory locations containing the running program (RAM)

• Secondary memory -- Permanent record of data often on a disk (e.g. Tape, Hard Disk, Floppy Disk etc. )

Page 7: OOPs Slides by Harish Kumar

Queries: [email protected] 7

Computer Memory

• Main Memory

– Long list of memory locations• Each contains zeros and ones• Can change during program execution

– Binary Digit or Bit• A digit that can only be zero or one

– Byte• Each memory location has eight bits

– Address • Number that identifies a memory location

Page 8: OOPs Slides by Harish Kumar

Queries: [email protected] 8

Larger Data Items

• Some data is too large for a single byte– Most integers and real numbers are

too large

– Address refers to the first byte

– Next few consecutive bytes can store the additional bits for larger data

Page 9: OOPs Slides by Harish Kumar

Queries: [email protected] 9

int sum(int[] x) {int sum(int[] x) { int sum = 0;int sum = 0; n = 0;n = 0; while (n < x.length) {while (n < x.length) { sum += x[n];sum += x[n]; }} return sum;return sum;}}

0010101010101000101010101010101010111110101010101111101011101010101110111010101011100010101010101000101010101010

......

Page 10: OOPs Slides by Harish Kumar

Queries: [email protected] 10

Data or Code?

• ‘A’ may look like 01000001

• 65 may look like 01000001

• An instruction may look like 01000001

• How does the computer know the meaning of 01000001?– Interpretation depends on the current instruction

Page 11: OOPs Slides by Harish Kumar

Queries: [email protected] 11

Secondary Memory

• Main memory stores instructions and data while a program is running.

• Secondary memory– Stores instructions and data between sessions

– A file stores data or instructions in secondary memory

Page 12: OOPs Slides by Harish Kumar

Queries: [email protected] 12

Computer Input

• Computer input consists of

– A program

– Some data

Page 13: OOPs Slides by Harish Kumar

Queries: [email protected] 13

High-level Languages

• Programming is the art of telling being what one wants the computer to do

• Common programming languages include …

C C++ Java Pascal Visual Basic FORTRAN COBOL Lisp etc.

• There are approximately 150 Computer High Level Languages

• 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

Page 14: OOPs Slides by Harish Kumar

Queries: [email protected] 14

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

Page 15: OOPs Slides by Harish Kumar

Queries: [email protected] 15

Incomplete list of C++ compliers

• Apple C++

• Bloodshed Dev – C++

• Borland C++

• Cygwin (GNU C++)

• Intel C++ for Linux

• GNU CC Source

• Borland C++

• HP C++

• IBM C++

• SUN C++

Page 16: OOPs Slides by Harish Kumar

Queries: [email protected] 16

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

intoThe machine language program the CPU can run

Page 17: OOPs Slides by Harish Kumar

Queries: [email protected] 17

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

– A Computer program is a set of instructions that directs a computer to perform tasks. Computer programmers use program development tools that generate these instructions automatically or use a programming language to write these instructions themselves.

Page 18: OOPs Slides by Harish Kumar

Queries: [email protected] 18

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

Page 19: OOPs Slides by Harish Kumar

Queries: [email protected] 19

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

Page 20: OOPs Slides by Harish Kumar

Queries: [email protected] 20

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

Page 21: OOPs Slides by Harish Kumar

Queries: [email protected] 21

Page 22: OOPs Slides by Harish Kumar

Queries: [email protected] 22

Session II

Page 23: OOPs Slides by Harish Kumar

Queries: [email protected] 23

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

Page 24: OOPs Slides by Harish Kumar

Queries: [email protected] 24

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

Page 25: OOPs Slides by Harish Kumar

Queries: [email protected] 25

Introduction to C++

• Where did C++ come from?– Derived from the C language

– C was derived from the B language

– B was derived from the BCPL language

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

Page 26: OOPs Slides by Harish Kumar

Queries: [email protected] 26

A Sample C++ Program

• A simple C++ program begins this way

#include <iostream.h>

int main(){

• And ends this way

return 0;}

Page 27: OOPs Slides by Harish Kumar

Queries: [email protected] 27

Page 28: OOPs Slides by Harish Kumar

Queries: [email protected] 33

Program Layout (1/3)

• Compiler accepts almost any pattern of line breaks and indentation

• Programmers format programs so they are easy to read

– Place opening brace ‘{‘ and closing brace ‘}’ on a line by themselves– Indent statements – Use only one statement per line

Page 29: OOPs Slides by Harish Kumar

Queries: [email protected] 34

Program Layout (2/3)

• Variables are declared before they are used

– Typically variables are declared at the beginning of the program

– Statements (not always lines) end with a semi-colon

• Include Directives #include <iostream.h>– Tells compiler where to find information about items used in the program

– iostream is a library containing definitions of cin and cout

Page 30: OOPs Slides by Harish Kumar

Queries: [email protected] 35

Program Layout (3/3)

• To begin the main function of the program int main()

{ • To end the main function

return 0; }– Main function ends with a return statement

C++ source code is written with a text editor

Page 31: OOPs Slides by Harish Kumar

Queries: [email protected] 37

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

Page 32: OOPs Slides by Harish Kumar

Queries: [email protected] 39

Program Style - Comments

• // is the symbol for a single line comment– Comments are explanatory notes for the programmer– All text on the line following // is ignored by the compiler– Example: //calculate regular wages

gross_pay = rate * hours;

• /* and */ enclose multiple line comments– Example: /* This is a comment that spans

multiple lines without a comment symbol on the middle line */

Page 33: OOPs Slides by Harish Kumar

Queries: [email protected] 40

C++ Basics

Page 34: OOPs Slides by Harish Kumar

Queries: [email protected] 41

Overview

Variables and Assignments

Input and Output

Data Types and Expressions

Simple Flow of Control

Program Style

Page 35: OOPs Slides by Harish Kumar

Queries: [email protected] 42

Variables and Assignments

• Variables are like small blackboards– We can write a number on them

– We can change the number

– We can erase the number

• C++ variables are names for memory locations– We can write a value in them

– We can change the value stored there

– We cannot erase the memory location• Some value is always there

Page 36: OOPs Slides by Harish Kumar

Queries: [email protected] 43

Identifiers & Keywords

• Variables or function names are called identifiers• Choosing variable names

– Use meaningful names that represent data to be stored– First character must be

• a letter or underscore character

– Remaining characters must be• Letters, numbers, underscore character

• Keywords (also called reserved words)– Are used by the C++ language – Must be used as they are defined in the programming language– Cannot be used as identifiers

Page 37: OOPs Slides by Harish Kumar

Queries: [email protected] 44

Declaring Variables

• Declaration syntax:– Type_name Variable_1 , Variable_2, . . . ;

• Before use, variables must be declared

– Tells the compiler the type of data to store

Examples: int number_of_bars; double one_weight, total_weight;

– int is an abbreviation for integer.• could store 3, 102, 3211, -456, etc. Number_of_bars is of type integer

– double represents numbers with a fractional component• could store 1.34, 4.0, -345.6, etc. one_weight and total_weight are both of type

double

Page 38: OOPs Slides by Harish Kumar

Queries: [email protected] 45

Assignment Statement

• An assignment statement changes the value of a variable– Assignment statements end with a semi-colon– The single variable to be changed is always on the left of the

assignment operator ‘=‘– On the right of the assignment operator can be

• Constants -- age = 21;• Variables -- my_cost = your_cost;• Expressions -- circumference = diameter * 3.14159;

• The ‘=‘ operator in C++ is not an equal sign– Statement “bars = bars + 3;” cannot be true in algebra

Page 39: OOPs Slides by Harish Kumar

Queries: [email protected] 46

Initializing Variables

• Declaring a variable does not give it a value– Giving a variable its first value is initializing the variable

• Variables are initialized using assignment statements

double mpg; // declare the variable mpg = 26.3; // initialize the variable

• Declaration and initialization can be combined: double mpg = 26.3, area = 0.0 , volume;

Page 40: OOPs Slides by Harish Kumar

Queries: [email protected] 47

Input and Output

• A data stream is a sequence of data– Typically in the form of characters or numbers

• An input stream is data for the program to use– Typically originates

• at the keyboard, mouse, some hardware circuit etc

• at a file

• An output stream is the program’s output– Destination is typically

• the monitor, hardware circuit

• a file

Page 41: OOPs Slides by Harish Kumar

Queries: [email protected] 48

Output using cout

• cout is an output stream sending data to the monitor• The insertion operator "<<" inserts data into cout• Example:

cout << number_of_bars << " candy bars\n";– This line sends two items to the monitor

• The value of number_of_bars• The quoted string of characters " candy bars\n"

– The ‘\n’ causes a new line to be started following the ‘s’ in bars• A new insertion operator is used for each item of output

– Here arithmetic is performed in the cout statement cout << "Total cost is $" << (price + tax);

Page 42: OOPs Slides by Harish Kumar

Queries: [email protected] 52

Input Using cin

• cin is an input stream bringing data from the keyboard• The extraction operator (>>) removes data to be used• Example:

cin >> number_of_bars; cin >> one_weight;

• This code prompts the user to enter data then reads two data items from cin– The first value read is stored in number_of_bars– The second value read is stored in one_weight

Page 43: OOPs Slides by Harish Kumar

Queries: [email protected] 53

Reading Data From cin

• Multiple data items are separated by spaces

• Data is not read until the enter key is pressed– Allows user to make corrections

• Example: cin >> v1 >> v2 >> v3;

– Requires three space separated values

– User might type 34 45 12 <enter key>

Page 44: OOPs Slides by Harish Kumar

Queries: [email protected] 54

Designing Input and Output

• Prompt the user for input that is desired– cout statements provide instructions

cout << "Enter your age: ";cin >> age;

• Notice the absence of a new line before using cin

• Echo the input by displaying what was read– Gives the user a chance to verify data

cout << age << " was entered." << endl;

Page 45: OOPs Slides by Harish Kumar

Queries: [email protected] 55

Data Types and Expressions

• 2 and 2.0 are not the same number– A whole number such as 2 is of type int

– A real number such as 2.0 is of type double

• Numbers of type int are stored as exact values

• Numbers of type double may be stored as approximate values due to limitations on number of significant digits that can be represented

• Type int does not contain decimal points• Examples: 34 45 1 89

Page 46: OOPs Slides by Harish Kumar

Queries: [email protected] 56

Writing Double Constants

• Type double can be written in two ways

– Simple form must include a decimal point• Examples: 34.1 23.0034 1.0 89.9

– Floating Point Notation (Scientific Notation)• Examples: 3.41e1 means 34.1

3.67e17 means 367000000000000000.0 5.89e-6 means 0.00000589

– Number left of e does not require a decimal point– Exponent cannot contain a decimal point

Page 47: OOPs Slides by Harish Kumar

Queries: [email protected] 62

Session III

Page 48: OOPs Slides by Harish Kumar

Queries: [email protected] 63

Type Casting

• Problem with integer division:

int total_candy = 9, number_of_people = 4;double candy_per_person;candy_per_person = total_candy / number_of_people;

– candy_per_person = 2, not 2.25

• A Type Cast produces a value of one type from another type– double(total_candy) produces a double representing the integer value of

total_candy

Page 49: OOPs Slides by Harish Kumar

Queries: [email protected] 66

Operators

• Arithmetic operators:--: + - * / %

• Comparison:--: = = != < > >= <=

• Logical:--: && || !

• Assignment:--: =

• Bitwise:--: & | ~ ^

• Shortcuts:--: += *= - = (etc.)

• Other:--: << >> ?: -> etc.

Page 50: OOPs Slides by Harish Kumar

Queries: [email protected] 67

Operators

• The unary operators ++ and -- :--: ++ increment by 1

--: -- decrement by 1

• The language C++ got its name by this operator!

• i++ and ++i have different behaviour

Page 51: OOPs Slides by Harish Kumar

Queries: [email protected] 68

Results of Operators

• Arithmetic operators can be used with any numeric type

• An operand is a number or variable used by the operator

• Result of an operator depends on the types of operands– If both operands are int, the result is int

– If one or both operands are double, the result is double

Page 52: OOPs Slides by Harish Kumar

Queries: [email protected] 71

Integer Remainders

• % operator gives the remainder from integer division

int dividend = 5, divisor = 3, remainder; remainder = dividend % divisor;

The value of remainder is 2

Page 53: OOPs Slides by Harish Kumar

Queries: [email protected] 74

Control Statements

Page 54: OOPs Slides by Harish Kumar

Queries: [email protected] 78

Page 55: OOPs Slides by Harish Kumar

Queries: [email protected] 79

Boolean Expressions

• Boolean expressions are expressions that are either true or false

• Boolean expressions can be combined using && (AND) and || (OR) operator

Page 56: OOPs Slides by Harish Kumar

Queries: [email protected] 81

&& and ||

&&• Syntax: (Comparison_1) && (Comparison_2)

• Example: if ( (2 < x) && (x < 7) )

||• Syntax: (Comparison_1) || (Comparison_2)

• Example: if ( (x= =1) || (x= =y) )

Page 57: OOPs Slides by Harish Kumar

Queries: [email protected] 82

NOT

• ! -- negates any boolean expression– !( x < y)

• True if x is NOT less than y

– !(x = = y)• True if x is NOT equal to y

• ! Operator can make expressions difficult to understand…use only when appropriate

Page 58: OOPs Slides by Harish Kumar

Queries: [email protected] 88

Page 59: OOPs Slides by Harish Kumar

Queries: [email protected] 90

Page 60: OOPs Slides by Harish Kumar

Queries: [email protected] 91

For loop

for (expression_1; expression_2; expression_3)

{ statements; }

Example: 1. for (int i=0; i < count; i++)

{ printf (“I=%d”, i); }

2. for (int i=0, j=count-1; i < count && j>ii; i++, j--)

{ statements; }

• Nested loops can also be used.

Page 61: OOPs Slides by Harish Kumar

Queries: [email protected] 92

Break & Continue Statements

• Common need is to either break or continue with loop.

• Continue goes to next iteration of loop

• Break steps out of loop

Page 62: OOPs Slides by Harish Kumar

Queries: [email protected] 94

Array

• A collection of elements of same type

• E.g. float a[100] -- Access 1st element using a[0]

float a[ ] = {1.2, 2.90, 3.4} -- Complier will calculate dim.

Multi – dimensional arrays:

float a[10][20]

• Elements appear row wise (In FORTRAN column wise)

• Run time array size: float *x = new float [n]

Page 63: OOPs Slides by Harish Kumar

Queries: [email protected] 95

Session IV

Page 64: OOPs Slides by Harish Kumar

Queries: [email protected] 96

Functions

Page 65: OOPs Slides by Harish Kumar

Queries: [email protected] 97

Function Call Syntax

• Function_name (Argument_List)

– Argument_List is a comma separated list:

(Argument_1, Argument_2, … , Argument_Last)

• Example:

– side = sqrt(area);

– cout << “2.5 to the power 3.0 is “ << pow(2.5, 3.0);

Page 66: OOPs Slides by Harish Kumar

Queries: [email protected] 98

Page 67: OOPs Slides by Harish Kumar

Queries: [email protected] 99

Programmer-Defined Functions

• Two components of a function definition– Function declaration (or function prototype)

• Shows how the function is called• Must appear in the code before the function can be called• Syntax:

Type_returned Function_Name(Parameter_List);

– Function definition• Describes how the function does its task• Can appear before or after the function is called• Syntax:

Type_returned Function_Name(Parameter_List) { //code to make the function work }

;

Page 68: OOPs Slides by Harish Kumar

Queries: [email protected] 100

Function Declaration

• Tells the return type• Tells the name of the function• Tells how many arguments are needed• Tells the types of the arguments• Tells the formal parameter names (optional)

– Formal parameters are like placeholders for the actual arguments used when the function is called

• Example:double total_cost(int number_par, double price_par);

Page 69: OOPs Slides by Harish Kumar

Queries: [email protected] 101

Function Definition

• Provides the same information as the declaration • Describes how the function does its task

• Example:double total_cost(int number_par, double price_par){ const double TAX_RATE = 0.05; double subtotal = price_par * number_par; return (subtotal + subtotal * TAX_RATE);}

function header

function body

Page 70: OOPs Slides by Harish Kumar

Queries: [email protected] 102

The Return Statement

• Ends the function call• Returns the value calculated by the function• Syntax:

return expression;– expression performs the calculation

or– expression is a variable containing the calculated value

• Example: return (subtotal + subtotal * TAX_RATE);

Page 71: OOPs Slides by Harish Kumar

Queries: [email protected] 103

The Function Call

• Tells the name of the function to use

• Lists the arguments

• Is used in a statement where the returned value makes sense

• Example:

double bill = total_cost(number, price);

Page 72: OOPs Slides by Harish Kumar

Queries: [email protected] 104

Page 73: OOPs Slides by Harish Kumar

Queries: [email protected] 105

Alternate Declarations

• Two forms for function declarations1. List formal parameter names2. List types of formal parmeters, but not names– First aids description of the function in comments

• Examples: double total_cost(int number_par, double price_par);

double total_cost(int, double);

• Function headers must always list formal parameter names!

Page 74: OOPs Slides by Harish Kumar

Queries: [email protected] 106

Order of Arguments

• Compiler checks that the types of the arguments are correct and in the correct sequence.

• Compiler cannot check that arguments are in the correct logical order

• Example: Given the function declaration: char grade(int received_par, int min_score_par);

int received = 95, min_score = 60; cout << grade( min_score, received);

– Produces a faulty result because the arguments are not in the correct logical order.

Page 75: OOPs Slides by Harish Kumar

Queries: [email protected] 107

Page 76: OOPs Slides by Harish Kumar

Queries: [email protected] 108

Passing Arguments

• Pass by value

• Pass by address

• Pass by reference

• Arguments for pass by reference & pass by address must be variables, not numbers

Page 77: OOPs Slides by Harish Kumar

Queries: [email protected] 109

Call Comparisons Call By Reference vs Value

• Call-by-reference– The function call:

f(age);

void f(int& ref_par);

MemoryName Location Contents

age 1001 34

initial 1002 A

hours 1003 23.5

1004

• Call-by-value– The function call:

f(age);

void f(int var_par);

Page 78: OOPs Slides by Harish Kumar

Queries: [email protected] 110

Mixed Parameter Lists

• Call-by-value and call-by-reference parameters can be mixed in the same function

• Example:void good_stuff(int& par1, int par2, double& par3);

– par1 and par3 are call-by-reference formal parameters• Changes in par1 and par3 change the argument variable

– par2 is a call-by-value formal parameter• Changes in par2 do not change the argument variable

Page 79: OOPs Slides by Harish Kumar

Queries: [email protected] 111

void-Functions

• A subtask might produce– No value

– One value

– More than one value

• We have seen how to implement functions that return one or more values

• A void-function implements a subtask that returns no value or more than one value

Page 80: OOPs Slides by Harish Kumar

Queries: [email protected] 112

Page 81: OOPs Slides by Harish Kumar

Queries: [email protected] 113

Using a void-Function

• void-function calls are executable statements– They do not need to be part of another statement– They end with a semi-colon

• Example: show_results(32.5, 0.3);

NOT: cout << show_results(32.5, 0.3);

Page 82: OOPs Slides by Harish Kumar

Queries: [email protected] 115

Page 83: OOPs Slides by Harish Kumar

Queries: [email protected] 116

The Main Function

• The main function in a program is used like a void function…do you have to end the program with a return-statement?

– Because the main function is defined to return a value of type int, the return is needed

– C++ standard says the return 0 can be omitted, but many compilers still require it

Page 84: OOPs Slides by Harish Kumar

Queries: [email protected] 117

Session V

Page 85: OOPs Slides by Harish Kumar

Queries: [email protected] 118

Default Arguments

• When function is called with less parameters, defaults are used

• Variables lacking default must be written first.

• Also possible:

void abc ( int = input());

Page 86: OOPs Slides by Harish Kumar

Queries: [email protected] 119

Overloading Function Names

• C++ allows more than one definition for the same function name

– Very convenient for situations in which the “same” function is needed for different numbers or types of arguments

• Polymorphism???

Page 87: OOPs Slides by Harish Kumar

Queries: [email protected] 120

Overloading Examples

• double avg(double n1, double n2){ return ((n1 + n2) / 2);}

• double avg(double n1, double n2, double n3){ return (( n1 + n2 + n3) / 3);}– Compiler checks the number and types of arguments in the function call to decide which

function to use

cout << avg( 10, 20, 30);

uses the second definition

Page 88: OOPs Slides by Harish Kumar

Queries: [email protected] 121

Overloading Details

• Overloaded functions

– Must have different numbers of formal parameters

AND / OR

Must have at least one different type of parameter

Page 89: OOPs Slides by Harish Kumar

Queries: [email protected] 122

Page 90: OOPs Slides by Harish Kumar

Queries: [email protected] 123

Functions Calling Functions

• A function body may contain a call to another function– The called function declaration must still appear before it is called

• Functions cannot be defined in the body of another function

– Example: void order(int& n1, int& n2) { if (n1 > n2) swap_values(n1, n2); }

• swap_values called if n1 and n2 are not in ascending order

• After the call to order, n1 and n2 are in ascending order

A function can call to itself (Recursion)

Page 91: OOPs Slides by Harish Kumar

Queries: [email protected] 124

Procedural Abstraction

• The Black Box Analogy– A black box refers to something that we know how to use, but the method of

operation is unknown– A person using a program needs to know what the program does, not how it does it

• Functions and the Black Box Analogy– A programmer who uses a function needs to know what the function does, not how it

does it

– A programmer needs to know what will be produced if the proper arguments are put into the box

Page 92: OOPs Slides by Harish Kumar

Queries: [email protected] 125

Information Hiding

• Designing functions as black boxes is an example of information hiding– The function can be used without knowing how it is coded

– The function body can be “hidden from view”

• Also allows us– To change or improve a function definition without forcing programmers

using the function to change what they have done

– To know how to use a function simply by reading the function declaration and its comment

Page 93: OOPs Slides by Harish Kumar

Queries: [email protected]

Classes & Objects

Page 94: OOPs Slides by Harish Kumar

Queries: [email protected] 127

What is Object Oriented Programming?

• Identifying objects and assigning responsibilities to these objects.

• Objects communicate to other objects by sending messages.

• Messages are received by the methods of an object

Page 95: OOPs Slides by Harish Kumar

Queries: [email protected] 128

What is Object?

An object is like a black box.

The internal details are hidden.

• an object represents an individual, identifiable item, unit, or entity with a well-defined role in the problem domain.

• The two parts of an object

Object = Data + Methods

Page 96: OOPs Slides by Harish Kumar

Queries: [email protected] 129

The two steps of Object Oriented Programming

• Making Classes: Creating, extending or reusing classes.

• Making Objects interact: Creating objects from classes and defining their relationships.

Page 97: OOPs Slides by Harish Kumar

Queries: [email protected] 130

Why Create Objects?

• Keeps all related info (i.e., data) together

• Refer to all the related info by one name

• Protect the information

• Hide methods that use or change the info

• Keep methods together with their related info

Page 98: OOPs Slides by Harish Kumar

Queries: [email protected] 133

Three Roles Related to Classes

• Class Provider – made or purchased– need for documentation of the class -- API

• Class User– programmer or development team

• Program User or End User

Page 99: OOPs Slides by Harish Kumar

Queries: [email protected] 134

Creating a Simple Class

class Change

{ private:

int rupees, dollars, pounds;

public:

int getRupees() { return rupees; }

int getDollars() { return dollars; }

int getPounds() { return pounds; }

…...

void printChange()

{ cout << "\nRupees: " << rupees << " Dollars: " << dollars << “

Pounds: " << pounds << endl; }

};

Page 100: OOPs Slides by Harish Kumar

Queries: [email protected] 135

Points of Care/Caution

• keyword class is in lower case

• no semicolon after the class name

• a semicolon after closing brace

• private extends until the next word public or till the end of the class definition

Page 101: OOPs Slides by Harish Kumar

Queries: [email protected] 136

Classes & Objects

• All the objects of a class may have different data values, but their allowed behaviours are the same.

• Class is a blue print for objects

• A class is defined by a unique name, attributes and methods

• An object is defined by identity, state and behaviour

Page 102: OOPs Slides by Harish Kumar

Queries: [email protected] 137

Instantiating an Object

• The class definition does not create any objects

• Instantiating is done just like declaring a variable of a built in data type

• Instantiating is done by a constructor– If the "class provider" does not provide a constructor, then the

C++ compiler provides a default one automatically– The default constructor does not provide values to the data

members

Page 103: OOPs Slides by Harish Kumar

Queries: [email protected] 139

Defining the Member Function Outside the Class

int main()

{

….

} //end of main function

//DEFINE MEMBER FUNCTION OUTSIDE THE CLASS

void Change::addChange(Change myChange) // scope resolution

{

rupees += myChange.rupees; //can refer to data members directly

dollars += myChange.dollars;

pounds += myChange.pounds;

}

…. //another member function definition here

Page 104: OOPs Slides by Harish Kumar

Queries: [email protected] 140

Points to Note about Defining Member Functions Outside the Class Definition

• Need to use the scope resolution operator to identify which class the function is associated with

• Need to specify return type and formal parameters the same as given in declaration

• Within the function you can refer to the data members of the receiving object using the data member names

Page 105: OOPs Slides by Harish Kumar

Queries: [email protected] 142

Session VI

Page 106: OOPs Slides by Harish Kumar

Queries: [email protected] 143

Class with a user defined default constructor

The syntax for a constructor is similar as for a method, but:• It has the same name as the class.• It has no return value.Example:class Change{private:

int rupees, dollars, pounds;…..

public:Change ( )

{ rupees=0; dollars=0; pounds = 0; cout <<“Object created.”; }…..

};

Page 107: OOPs Slides by Harish Kumar

Queries: [email protected] 144

Class with a parameterized constructor.

class Change{private:

int rupees, dollars, pounds;…..

public:Change (int initvalue)

{ rupees=initvalue; dollars=initvalue; pounds = initvalue; cout <<“Object created.”; } …..

};This constructor can be used as follows:

– Change firstObject(10);

Page 108: OOPs Slides by Harish Kumar

Queries: [email protected] 145

Class with a copy constructor.

class Change{ private: int rupees, dollars, pounds; public:

Change (int initvalue) { rupees=initvalue; dollars=initvalue; pounds = initvalue; cout <<“Object created.”;} Change (Change& smobject) { rupees = smobject.get(); }

…..};This constructor can be used as follows:

Change firstObject (10);Change secondObject (firstObject);

Page 109: OOPs Slides by Harish Kumar

Queries: [email protected] 146

Private Constructor & Destructor

• Must be called explicitly.

• Use this operator.

class Change

{ private:

int rupees, dollars, pounds;

Change (int initvalue)

{ rupees=initvalue; dollars=initvalue; pounds = initvalue; }

public:

show (int i)

{ this -> Change :: Change (i) }

};

Page 110: OOPs Slides by Harish Kumar

Queries: [email protected] 148

Encapsulation

• Encapsulation is the practice of including in an object everything it needs hidden from other objects. The internal state is usually not accessible by other objects.

• Preventing unauthorized access to some piece of information or functionality.

• Encapsulation prevents mistakes, not espionage. It is not a security device.

Page 111: OOPs Slides by Harish Kumar

Queries: [email protected] 149

Breaking Encapsulation – Friends

• C++ provides a way to enable a class or function to access the private parts of another class.

• This is done by using the friend key-word in the class declaration. class Change{ friend void xyz (Change& smobject); friend class Change2; private: int rupees, dollars, pounds; public:

Change (int initvalue) { rupees=initvalue; dollars=initvalue; pounds = initvalue; cout <<“Object created.”;} };

Page 112: OOPs Slides by Harish Kumar

Queries: [email protected] 150

Friends of the Change Class

• The function xyz can now access the private attributes:

void xyz(Change& c)

{ c.rupees = c.rupees + 5; }

• The class Change2 can now access the private attributes rupees etc..:

class Change2

{

void convert(Change& c )

{ c.rupees = c.dollar * 45; }

};

Page 113: OOPs Slides by Harish Kumar

Queries: [email protected] 151

Class with in class

• A::B::C xyz

• xyz is object of innermost class C.

Page 114: OOPs Slides by Harish Kumar

Queries: [email protected] 152

Session VII

Page 115: OOPs Slides by Harish Kumar

Queries: [email protected] 153

Inheritance

Page 116: OOPs Slides by Harish Kumar

Queries: [email protected] 154

What is Inheritance?

• Classes can inherit attributes and methods from other classes

• Inheriting class can add extra attributes and / or methods of its own

• Extends the functionality of an existing class

Page 117: OOPs Slides by Harish Kumar

Queries: [email protected] 155

C++ Syntax

• A simple base class: with 1 private attribute & 2 public methods

class BaseClass

{

private:

int x;

public:

void setX ( int x_in );

int getX ( );

};

Page 118: OOPs Slides by Harish Kumar

Queries: [email protected] 156

C++ Syntax: public inheritance

• Public inheritance means that objects of the derived class can access the public methods and attributes of the base class

class DerivedClass : public BaseClass

{

private: int y;

public: void setY ( int y_in );

int getY ( );

};

Page 119: OOPs Slides by Harish Kumar

Queries: [email protected] 157

C++ Syntax: public inheritance

• Object of the inheritance class can access methods of the derived class and also methods of the base classmain ( ){ BaseClass base_object; DerivedClass derived_object;

base_object.setX(7);

derived_object.setX(12); derived_object.setY(1);}

Page 120: OOPs Slides by Harish Kumar

Queries: [email protected] 158

C++ Syntax: private inheritance

• Private inheritance means that objects of the derived class can’t access the public methods and attributes of the base class – but the methods of the derived class can !!!!!

class DerivedClass : private BaseClass{ private:

int y;

public: void setY(int y_in); int getY();

};

Page 121: OOPs Slides by Harish Kumar

Queries: [email protected] 159

C++ Syntax: the ‘protected’ keyword

• An object of a publicly derived class can access the public methods of the base class, but not the private attributes

• Changing the private keyword in the base class to protected makes the attributes available to derived classes

Page 122: OOPs Slides by Harish Kumar

Queries: [email protected] 160

Base Class Access Mode

Derived Class Access Mode

private derivation

public derivation

protected derivation

public private public protected

private Not Inherited Not Inherited Not Inherited

protected private protected protected

Page 123: OOPs Slides by Harish Kumar

Queries: [email protected] 161

C++ Syntax: inheriting constructors

• A derived class always inherits the constructor of the base class. The base class constructor is called first.

• If the base class constructor takes no parameters then the inheritance is implicit - you don’t need to do anything.

• If the base class constructor takes parameters then each derived class needs to declare a constructor with the same parameters. You can pass the arguments given to the derived class constructor to the constructor for the base class

Page 124: OOPs Slides by Harish Kumar

Queries: [email protected] 162

C++ Syntax: inheriting constructors

• Base class declares a constructor that takes a char pointer parameter

class Customer

{

Customer (char * name_in);

};

• Derived class declares a constructor that takes the same char pointer parameter

Class AccountCustomer : public Customer

{

AccountCustomer(char * name_in);

};

Page 125: OOPs Slides by Harish Kumar

Queries: [email protected] 163

C++ Syntax: inheriting constructors

• In the implementation of the constructor for the derived class, the parameter passed to the derived class constructor is passed down to the base class constructor.

AccountCustomer :: AccountCustomer(char * name_in) : Customer(name_in)

{

//main body of constructor..

}

Page 126: OOPs Slides by Harish Kumar

Queries: [email protected] 164

C++ Syntax: inheriting destructors

• A derived class always inherits the destructor of the base class. The derived class destructor is called first. This is the reverse of the sequence for constructors

• Because destructors never take an argument there is no issue with inheritance of destructor parameters.

Page 127: OOPs Slides by Harish Kumar

Queries: [email protected] 165

Polymorphism

• From the Greek:– Polus + Morphe = Polumorphos

(many ) (shape/form)

• In object-oriented computing it means: different forms of data being handled by the same type of process.

• Example: The operator + has a different meaning in the expression 2 + 3 (add two integers) than in 1.7 + 3.3 (add two floating point numbers)

Page 128: OOPs Slides by Harish Kumar

Queries: [email protected] 166

Types of Polymorphism

Three types of polymorphism:

a) Function Overloading, with the special case of operator overloading. It can also be applied in non-object oriented contexts

b) Method Overriding

c) Run-time Polymorphism (Dynamic Binding)

Method overriding and run-time polymorphism are specific to inheritance hierarchies and object oriented programming

Page 129: OOPs Slides by Harish Kumar

Queries: [email protected] 168

Operator Overloading

• Operators such as +, -, *, <<, =, etc. can be seen as “functions”. That means we can overload operators.

• The C++ syntax uses “function names” prefixed with “operator” for overloading operators.

Page 130: OOPs Slides by Harish Kumar

Queries: [email protected] 169

Overloading Operators - Example

Return_Type operator operator_symbol (parameters)

{

statements;

}

Page 131: OOPs Slides by Harish Kumar

Queries: [email protected] 170

Overloading Operators - Example

class Change

{ private:

int rupees, dollars, pounds;

public:

Change operator + (Change other)

{ change temp;

temp.rupees = rupee + other.rupees;

temp.dollar = dollar + other.dollar;

temp.pounds = pounds + other.pounds;

return temp;

}

};

Page 132: OOPs Slides by Harish Kumar

Queries: [email protected] 171

Operator Overloading

• Change A, B, C;

C = A + B

A will invoke operator function + and B will be passed as argument.

• Note that "=" has already a default behaviour. When "overloaded" it will be in fact overridden.

Page 133: OOPs Slides by Harish Kumar

Queries: [email protected] 172

Polymorphic Pointers

• A pointer of a parent class is allowed to point to an object of the child class. E.g.

class Vehicle { ... };

class Car : public Vehicle { ... };

main()

{ Vehicle vp = new Car(); }

Page 134: OOPs Slides by Harish Kumar

Queries: [email protected] 173

Overriding Methods

• Methods in the parent class can be redefined in the child class.

class Vehicle { void move(int i); };class Car : public Vehicle { void move(int i); };

main(){ Vehicle vp = new Car(); vp->move(100);}

Page 135: OOPs Slides by Harish Kumar

Queries: [email protected] 174

Overriding Methods

• Which of these two move() methods will be called?

1. Static type binding & also default behaviour.2. As vp is of type pointer to a Vehicle, the method of the Vehicle is called

Page 136: OOPs Slides by Harish Kumar

Queries: [email protected] 175

Overriding Methods – Virtual Keyword

class Vehicle { virtual void move(int i); };class Car : public Vehicle { virtual void move(int i); };

main(){ Vehicle vp = new Car(); vp->move(100);}– Allows dynamic binding.– As vp points to a Car object the method of the Car is called

Page 137: OOPs Slides by Harish Kumar

Queries: [email protected] 176

Abstract Methods & Classes

• Methods without any implementation (pure virtual methods).

class Vehicle { virtual void move(int i) = 0; };class Car : public Vehicle { virtual void move(int i); };

main(){ Vehicle vp = new Car(); vp->move(100);}

Vehicle objects cannot be instantiated (but Car objects).

Page 138: OOPs Slides by Harish Kumar

Queries: [email protected] 177

Vectors

• Vectors are like arrays that can change size as your program runs

• Vectors, like arrays, have a base type

• To declare an empty vector with base type int: vector<int> v;– <int> identifies vector as a template class

– You can use any base type in a template class: vector<float> v;

Page 139: OOPs Slides by Harish Kumar

Queries: [email protected] 178

Initializing vector Elements

• Elements are added to a vector using the member function push_back

– push_back adds an element in the next available position

– Example: vector<double> sample; sample.push_back(0.0); sample.push_back(1.1); sample.push_back(2.2);

Page 140: OOPs Slides by Harish Kumar

Queries: [email protected] 179

The size Of A vector

• The member function size returns the number of elements in a vector

– Example: To print each element of a vector given the previous vector initialization: for (int i= 0; i < sample.size( ); i++) cout << sample[i] << endl;

Page 141: OOPs Slides by Harish Kumar

Queries: [email protected] 180

The Type unsigned int

• The vector class member function size returns an unsigned int

– Unsigned int's are nonnegative integers

– Some compilers will give a warning if the previous for-loop is not changed to:

for (unsigned int i= 0; i < sample.size( ); i++) cout << sample[i] << endl;

Page 142: OOPs Slides by Harish Kumar

Queries: [email protected] 181

Alternate vector Initialization

• A vector constructor exists that takes an integer argument and initializes that number of elements

– Example: vector<int> v(10);

initializes the first 10 elements to 0 v.size( ) would return 10

• [ ]'s can now be used to assign elements 0 through 9

• push_back is used to assign elements greater than 9

Page 143: OOPs Slides by Harish Kumar

Queries: [email protected] 182

The vector Library

• To use the vector class– Include the vector library

#include <vector>

– Vector names are placed in the standard namespace so the usual using directive is needed:

using namespace std;

Page 144: OOPs Slides by Harish Kumar

Queries: [email protected] 183

vector Issues

• Attempting to use [ ] to set a value beyond the size of a vector may not generate an error– The program will probably misbehave

• The assignment operator with vectors does an element by element copy of the right hand vector– For class types, the assignment operator must make independent copies

Page 145: OOPs Slides by Harish Kumar

Queries: [email protected] 184

vector Efficiency

• A vector's capacity is the number of elements allocated in memory– Accessible using the capacity( ) member function

• Size is the number of elements initialized

• When a vector runs out of space, the capacity is automatically increased– A common scheme is to double the size of a vector

• More efficient than allocating smaller chunks of memory

Page 146: OOPs Slides by Harish Kumar

Queries: [email protected] 185

Controlling vector Capacity

• When efficiency is an issue– Member function reserve can increase the capacity of a vector

• Example: v.reserve(32); // at least 32 elements v.reserve(v.size( ) + 10); // at least 10 more

– resize can be used to shrink a vector• Example: v.resize(24); //elements beyond 24 are lost