Vous êtes sur la page 1sur 146

Computer Programming

Harish Kumar, UIET, Panjab University, Chandigarh

Queries: harishk@pu.ac.in
Session I

Queries: harishk@pu.ac.in 2
Computer Fundamentals

Queries: harishk@pu.ac.in 3
Software

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

Queries: harishk@pu.ac.in 4
Queries: harishk@pu.ac.in 5
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. )

Queries: harishk@pu.ac.in 6
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

Queries: harishk@pu.ac.in 7
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

Queries: harishk@pu.ac.in 8
int sum(int[] x) {
int sum = 0; 00101010101010
n = 0; 10101011111010
while (n < x.length) {
sum += x[n];
11101010101110
} 00101010101010
return sum; ...
}

Queries: harishk@pu.ac.in 9
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

Queries: harishk@pu.ac.in 10
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

Queries: harishk@pu.ac.in 11
Computer Input
• Computer input consists of

– A program

– Some data

Queries: harishk@pu.ac.in 12
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

Queries: harishk@pu.ac.in 13
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

Queries: harishk@pu.ac.in 14
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++

Queries: harishk@pu.ac.in 15
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

Queries: harishk@pu.ac.in 16
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.

Queries: harishk@pu.ac.in 17
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

Queries: harishk@pu.ac.in 18
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

Queries: harishk@pu.ac.in 19
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

Queries: harishk@pu.ac.in 20
Queries: harishk@pu.ac.in 21
Session II

Queries: harishk@pu.ac.in 22
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

Queries: harishk@pu.ac.in 23
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

Queries: harishk@pu.ac.in 24
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++

Queries: harishk@pu.ac.in 25
A Sample C++ Program
• A simple C++ program begins this way
#include <iostream.h>
int main()
{

• And ends this way


return 0;
}

Queries: harishk@pu.ac.in 26
Queries: harishk@pu.ac.in 27
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

Queries: harishk@pu.ac.in 33
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

Queries: harishk@pu.ac.in 34
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

Queries: harishk@pu.ac.in 35
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

Queries: harishk@pu.ac.in 37
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
*/

Queries: harishk@pu.ac.in 39
C++ Basics

Queries: harishk@pu.ac.in 40
Overview
 Variables and Assignments

 Input and Output

 Data Types and Expressions

 Simple Flow of Control

 Program Style

Queries: harishk@pu.ac.in 41
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

Queries: harishk@pu.ac.in 42
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

Queries: harishk@pu.ac.in 43
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

Queries: harishk@pu.ac.in 44
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
Queries: harishk@pu.ac.in 45
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;

Queries: harishk@pu.ac.in 46
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

Queries: harishk@pu.ac.in 47
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);

Queries: harishk@pu.ac.in 48
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

Queries: harishk@pu.ac.in 52
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>

Queries: harishk@pu.ac.in 53
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;

Queries: harishk@pu.ac.in 54
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

Queries: harishk@pu.ac.in 55
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

Queries: harishk@pu.ac.in 56
Session III

Queries: harishk@pu.ac.in 62
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

Queries: harishk@pu.ac.in 63
Operators

• Arithmetic operators: • Bitwise:


--: + - * / % --: & | ~ ^
• Comparison: • Shortcuts:
--: == != < > >= <= --: += *= - = (etc.)
• Logical: • Other:
--: && || ! --: << >> ?: -> etc.
• Assignment:
--: =

Queries: harishk@pu.ac.in 66
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

Queries: harishk@pu.ac.in 67
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

Queries: harishk@pu.ac.in 68
Integer Remainders

• % operator gives the remainder from integer division

int dividend = 5, divisor = 3, remainder;


remainder = dividend % divisor;
The value of remainder is 2

Queries: harishk@pu.ac.in 71
Control Statements

Queries: harishk@pu.ac.in 74
Queries: harishk@pu.ac.in 78
Boolean Expressions

• Boolean expressions are expressions that are either true or false

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


(OR) operator

Queries: harishk@pu.ac.in 79
&& and ||

&&
• Syntax: (Comparison_1) && (Comparison_2)
• Example: if ( (2 < x) && (x < 7) )

||
• Syntax: (Comparison_1) || (Comparison_2)
• Example: if ( (x= =1) || (x= =y) )

Queries: harishk@pu.ac.in 81
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

Queries: harishk@pu.ac.in 82
Queries: harishk@pu.ac.in 88
Queries: harishk@pu.ac.in 90
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.

Queries: harishk@pu.ac.in 91
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

Queries: harishk@pu.ac.in 92
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]

Queries: harishk@pu.ac.in 94
Session IV

Queries: harishk@pu.ac.in 95
Functions

Queries: harishk@pu.ac.in 96
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);

Queries: harishk@pu.ac.in 97
Queries: harishk@pu.ac.in 98
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
}

Queries: harishk@pu.ac.in 99
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);

Queries: harishk@pu.ac.in 100


Function Definition
• Provides the same information as the declaration
• Describes how the function does its task
function header
• 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 body
Queries: harishk@pu.ac.in 101
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);

Queries: harishk@pu.ac.in 102


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);

Queries: harishk@pu.ac.in 103


Queries: harishk@pu.ac.in 104
Alternate Declarations
• Two forms for function declarations
1. List formal parameter names
2. 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!

Queries: harishk@pu.ac.in 105


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.
Queries: harishk@pu.ac.in 106
Queries: harishk@pu.ac.in 107
Passing Arguments

• Pass by value

• Pass by address

• Pass by reference

• Arguments for pass by reference & pass by address must


be variables, not numbers

Queries: harishk@pu.ac.in 108


Call Comparisons Call By Reference vs Value
• Call-by-reference • Call-by-value
– The function call: – The function call:
f(age); Memory f(age);
Name Location Contents

age 1001 34
initial 1002 A
hours 1003 23.5
1004

void f(int var_par);


void f(int& ref_par);
Queries: harishk@pu.ac.in 109
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

Queries: harishk@pu.ac.in 110


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
Queries: harishk@pu.ac.in 111
Queries: harishk@pu.ac.in 112
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);

Queries: harishk@pu.ac.in 113


Queries: harishk@pu.ac.in 115
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

Queries: harishk@pu.ac.in 116


Session V

Queries: harishk@pu.ac.in 117


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());

Queries: harishk@pu.ac.in 118


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???

Queries: harishk@pu.ac.in 119


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

Queries: harishk@pu.ac.in 120


Overloading Details

• Overloaded functions

– Must have different numbers of formal parameters

AND / OR

Must have at least one different type of parameter

Queries: harishk@pu.ac.in 121


Queries: harishk@pu.ac.in 122
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)

Queries: harishk@pu.ac.in 123


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

Queries: harishk@pu.ac.in 124


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

Queries: harishk@pu.ac.in 125


Classes & Objects

Queries: harishk@pu.ac.in
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

Queries: harishk@pu.ac.in 127


What is Object?

• an object represents an individual,


identifiable item, unit, or entity with
a well-defined role in the problem
domain.
An object is like a
black box. • The two parts of an object
The internal details
are hidden. Object = Data + Methods

Queries: harishk@pu.ac.in 128


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.

Queries: harishk@pu.ac.in 129


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

Queries: harishk@pu.ac.in 130


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

Queries: harishk@pu.ac.in 133


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; }
};

Queries: harishk@pu.ac.in 134


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
Queries: harishk@pu.ac.in 135
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

Queries: harishk@pu.ac.in 136


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

Queries: harishk@pu.ac.in 137


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

Queries: harishk@pu.ac.in 139


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

Queries: harishk@pu.ac.in 140


Session VI

Queries: harishk@pu.ac.in 142


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.”; }
…..
};

Queries: harishk@pu.ac.in 143


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);

Queries: harishk@pu.ac.in 144


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);

Queries: harishk@pu.ac.in 145


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) }
};

Queries: harishk@pu.ac.in 146


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.

Queries: harishk@pu.ac.in 148


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.”;}
};

Queries: harishk@pu.ac.in 149


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; }
};

Queries: harishk@pu.ac.in 150


Class with in class

• A::B::C xyz
• xyz is object of innermost class C.

Queries: harishk@pu.ac.in 151


Session VII

Queries: harishk@pu.ac.in 152


Inheritance

Queries: harishk@pu.ac.in 153


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

Queries: harishk@pu.ac.in 154


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 ( );
};

Queries: harishk@pu.ac.in 155


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 ( );
};

Queries: harishk@pu.ac.in 156


C++ Syntax: public inheritance

• Object of the inheritance class can access methods of the derived


class and also methods of the base class
main ( )
{
BaseClass base_object;
DerivedClass derived_object;

base_object.setX(7);

derived_object.setX(12);
derived_object.setY(1);
}
Queries: harishk@pu.ac.in 157
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();
};

Queries: harishk@pu.ac.in 158


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

Queries: harishk@pu.ac.in 159


Base Class Derived Class Access Mode
Access Mode private public protected
derivation derivation derivation
public private public protected

private Not Inherited Not Inherited Not Inherited

protected private protected protected

Queries: harishk@pu.ac.in 160


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

Queries: harishk@pu.ac.in 161


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);
};

Queries: harishk@pu.ac.in 162


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..
}

Queries: harishk@pu.ac.in 163


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.

Queries: harishk@pu.ac.in 164


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)
Queries: harishk@pu.ac.in 165
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

Queries: harishk@pu.ac.in 166


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.

Queries: harishk@pu.ac.in 168


Overloading Operators - Example

Return_Type operator operator_symbol (parameters)


{
statements;
}

Queries: harishk@pu.ac.in 169


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;
}
};

Queries: harishk@pu.ac.in 170


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.

Queries: harishk@pu.ac.in 171


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(); }

Queries: harishk@pu.ac.in 172


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);
}

Queries: harishk@pu.ac.in 173


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

Queries: harishk@pu.ac.in 174


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

Queries: harishk@pu.ac.in 175


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).

Queries: harishk@pu.ac.in 176


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;

Queries: harishk@pu.ac.in 177


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);

Queries: harishk@pu.ac.in 178


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;

Queries: harishk@pu.ac.in 179


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;

Queries: harishk@pu.ac.in 180


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

Queries: harishk@pu.ac.in 181


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;

Queries: harishk@pu.ac.in 182


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

Queries: harishk@pu.ac.in 183


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

Queries: harishk@pu.ac.in 184


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

Queries: harishk@pu.ac.in 185

Vous aimerez peut-être aussi