You are on page 1of 613

History of C

• C was created by Dennis Ritchie at the AT & T


Bell Laboratories, USA in 1972
• Evolved from two previous programming
languages, BCPL (Basic Computer
Programming language, 1967) and B
(developed by Ken Thompson of Bell
Labs,1970 )
• Used to develop UNIX
• High level language
• Efficient, fast and highly portable, use less
memory
• Is a system programming language
• Case Sensetive
Character Set
• A Character is the smallest unit that provides meaningful
information to compiler
• Characters are combined to form
• Identifiers and keywords
• Data types
• Constants
• Declarations
• Expressions and statements
Types of character set
The C Character Set : It consists of
• Letters
• Digits
• White spaces
• Special Characters

Letters :
C language comprises the following set of letters to form a standard
program. They are :
• A to Z (Uppercase characters)
• a to z (lowercase characters)

Digits :
• C language comprises the following sequence of numbers to associate the
letters.
• 0 to 9 digits.
Tokens
• Smallest unit in a program/statement
• It makes the compiler understand what is written in the
program
• Example: main, (,), printf , (semicolon), etc..
• Tokens are broadly classified as:
Keywords
• Keywords are pre-defined words in a C compiler.
• In C there are certain reserved word that we
cannot declare as variable.
• These words are known as keywords
• Each keyword is meant to perform a specific
function in a C program.
• There are 32 keywords in C language.
• All keywords are written in lowercase only
Identifiers
• Identifiers are the fundamental building blocks
of a program
• Used to give names to variables, functions,
arrays, structures, etc.
• They are user-defined names and consist of a
sequence of letters and digits
• Rules for identifier naming:
• Valid characters are alphabets, digits, and underscore
• First character cannot be a digit
• Uppercase and lowercase are distinct
• Keywords cannot be used as identifier names
Examples
• Examples of legal identifiers:
• Student_Name
• StudentName
• Student_name
• Student1
• _student
• Examples of illegal identifiers :
• Student Name
• Name&Rollno
• 1st_student
Data types
• Data type is one of the most important attribute
of an identifier.
• It determines the possible values that an
identifier can have
• Each of the data types are represented
differently within the computer’s memory
• In C data type is broadly classified as:
• Basic data types
• Derived data types
• User defined data types
Data Types
Basic Data Types
Basic/primitive data types:

The five basic data types and their


corresponding keywords available in C are:
• Character(char)
• Integer(int)
• Floating point (float)
• Double floating point(double)
• No value available(void)
int
• It is used to store an integer quantity
• The type modifiers for the int data type are:
signed, unsigned, short, long .
Range of Data types
• TYPE BITWIDTH RANGE
• char 8 -128 to 127 (ASCII)
• int 16 -32768 to 32767
• float 32 -3.4E+38 to 3.4 E+38
• double 64 -1.7E+308 to 1.7 E+308
• void 0 valueless
• TYPE EXAMPLES

• char ‘A’ ‘b’ ‘$’ ‘9’

• int 1 250 4500

• float 3.5 42.56 345.6789

• double 3.5647290… 486.145875...

• void valueless
Integers
Integers
char
• It stores a single character of data belonging
to the C character set.
• It occupies 1 byte of memory
• The type modifiers for char are signed and
unsigned.
• Each char type has an equivalent integer
interpretation, so that a char is really a special
kind of short integer
• By default, char is unsigned.
Characters
float
• It is used to store real numbers with single
precision i.e. a precision of 6 digits after
decimal point.
• The type modifier for float is long
User defined data types:
•The C language provide the flexibility to the
user to create new data types.
•The newly created data types are called user

defined data type.


•The user defined data types that are available

in C are:
• Structure
• Union
• Enumeration
• Derived Data types:
• These data types are derived from the basic
data types . Derived data types that are
available in C are:
• Array type
• Function type etc.
Variable Declaration
Examples:
char name;
int x, y,z;
float number;
float n1, n2, sum;
double counter;
Variable Initialization
• Giving a value to a variable during the
variable’s declaration is called “variable
initialization.”
Syntax:
type variable_name = value;
Example:
int count = 100;
float grade = 3.75;
char status = ‘S’;
Declaration
• First step in c is declaring the variables
• Why???
• Ans: we need space to store data in
memory
• int x
• Compiler will allots a address to x and
Then compiler can store the data in that
Memory space.
Header Files
• Header files
• Contain function prototypes for library functions
• <stdlib.h> , <math.h> , etc
• Load with #include <filename>
• #include <math.h>
• Custom header files
• Create file with functions
• Save as filename.h
• Load in other files with #include "filename.h"
• Reuse functions
• Example #include<square.h>
Header Files
Comment
• Programmers insert comments to document
programs and improve program readability.

• Starts with /* and ends with */


Also for one line comment we use //

• Can be placed anywhere in the program.

• Comments are ignored by the C compiler.


Operators
• An operator is a symbol used to indicate a specific
operation on operands that yield a value. An operand is an
entity on which an operator acts.
• a+b
a and b are operands and + is operator
• C language operators are classified as:-
• Arithmetic operators.
• Relational operators.
• Logical/Boolean operators.
• Assignment operators
• Increment/decrement operators.
• Bitwise operators.
Arithmetic Operators
• Arithmetic operators:-
+, -, *, /, % are called arithmetic operators.

• Arithmetic expression:-
• An expression that involves arithmetic operators
and combines them constants and variables is
called an arithmetic expression.
• The result of an arithmetic expression is always a
numeric value.
Classification based on number of
Operands
Unary operator:-
• An operator that takes only one operand is called unary operator.
• E.g. Unary minus as in –2.5, &, sizeof operator, ++, --

Binary operator:-
• An operator that takes two operands to write an arithmetic expression is called
binary operator.
Binary operator Meaning
• + Plus
• - minus
• * multiplication
• / division
• % modulus operator for remainder used with integer
numbers.
<<, ==, &&
• Ternary operator:- (Conditional operator):-
• This is a special feature of C language.
• This case needs three operands.
• Operand1 ? operand2 : operand3;
• operand1 is evaluated first, if it results true ,
the value of operand2 is taken otherwise the
value of operand3 is taken for further
processing
Relational operator
• A relational operator is used to compare two
values and the result is always logical i.e.
either true or false.
• e.g. a>b return a value zero when the result is
false and a non-zero when it is true.
• Associativity Left to Right
Assignment Operators
• Assignment operator:-
• Assignment operator denoted as =, stores the
value of the expression on the right hand side
of the equal sign in the variable represented
by the left hand side of the equal sign.
• e.g. The statement sum = 4+7-8/2 will
store value 7 in the variable sum..
• Increment/Decrement operators:-
• The increment operator, ++, adds 1 to its operand
and – subtracts 1 from its operand.
• e.g. Let sum = 10;
• x=5;
• then
• sum = sum + (++x); yields 16
• sum = sum + (x++); yields 15
• sum = sum + (--x); yields 14
• sum = sum + (x--); yields 15
Increment and Decrement Operators
Logical operators
• A logical operator is used to connect relational expression or logical
expressions and returns the logical value i.e. true or false.
• The logical operators supported by C are

1. && Logical AND


E.g. x && y
if( marks>>=60 && age>=21)
printf(“ You are eligible for admission”);
2. | | Logical OR
x||y
3. ! Logical NOT
!x
• Rules for logical operators:-
• The output of a logical AND operation is true if its
both the operands are true. For all other
combinations the result is false.
• The output of logical OR operation is false if both the
operands are false. For all other combinations the
result is true.
• The logical NOT is a unary operator. It negates the
value of the operand.
• e.g:- If x=6 and y=9 then the expression (x<7) &&
(y>8) is true.
Conditional Operator
• Operand1 ? operand2 : operand3;
• operand1 is evaluated first, if it results true ,
the value of operand2 is taken otherwise the
value of operand3 is taken for further
processing.
• It is a Ternary operator.
Control Statements
• The C language programs until now follows a
sequential form of execution of statements.
• Many times it is required to alter the flow of the
sequence of instructions.
• C language provides statements that can alter the
flow of a sequence of instructions. These statements
are called control statements.
• These statements help to jump from one part of the
program to another. The control transfer may be
conditional or unconditional.
• The C conditional statements are the:
• if statement
• if-else statement
• switch statement
Logic of an if statement

conditi
on
evaluat
ed
tru
e fal
se
statement
The if Statement
• The if statement has the following syntax:
The condition must be a
boolean expression. It must
if is a C evaluate to either true or false.
reserved word

if ( condition
)
statement;

If the condition is true, the statement is executed.


If it is false, the statement is skipped.
• If student’s grade is greater than or equal to 60
Print “Passed”

• if ( grade >= 60 )
{
printf( "Passed\n" );
} /* end if */
Example
• Demonstration of IF Statement
1. Enter a number and print result if Number is
less than 0.

2. Calculation of Total Expenses by entering Qty


and Rate and if Qty>1000. Dis =10
IF-ELSE
• The if else is actually just on extension of the
general format of if statement.
• If the result of the condition is true, then program
statement 1 is executed, otherwise program
statement 2 will be executed.
• If any case either program statement 1 is executed
or program statement 2 is executed but not both
• When writing programs this else statement is so
frequently required that almost all programming
languages provide a special construct to handle this
situation.
If…Else Statement
if (a>b)
{

}
else
{

}
•the if part is executed if the test statement is true,

otherwise the else part is executed.


Logic of an if-else statement

conditi
on
evaluat
ed
tru fal
e se
statement1 statement2
The if-else Statement
• An else clause can be added to an if
statement to make an if-else statement
if ( condition
)
statement1;
else
statement2;
• If the condition is true, statement1 is executed; if the condition
is false, statement2 is executed
• One or the other will be executed, but not both
If…Else Statement
#include <stdio.h> //include the stdio.h header file in your program
void main () // start of the main
{
int num; // declare variable num as integer
printf ("Enter the number"); // message to the user
scanf ("%d", &num); // read the input number from keyboard
if (num < 0) // check whether number is less than zero
{
printf ("The number is negative"); // if it is less than zero then it is negative
}
else // else statement
{
printf ("The number is positive"); // if it is more than zero then the given number is positive
}
getch();
}
Nested if else Statements
• The statement executed as a result of an if statement or
else clause could be another if statement
• These are called nested if statements
• An else clause is matched to the last unmatched if (no
matter what the indentation implies)
• Braces can be used to specify the if statement to which an
else clause belongs
• Example: Enter 1 or 2
Nested if else
The switch Statement
• The switch statement provides another way to
decide which statement to execute next
• The switch statement evaluates an expression,
then attempts to match the result to one of
several possible cases
• Each case contains a value and a list of
statements
• The flow of control transfers to statement
associated with the first case value that matches
The switch Statement
• Often a break statement is used as the last
statement in each case's statement list
• A break statement causes control to transfer to
the end of the switch statement
• If a break statement is not used, the flow of
control will continue into the next case
• Sometimes this may be appropriate, but often
we want to execute only the statements
associated with one case
The switch Statement
• An example of a switch statement:
switch (option)
{
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
default:
otherCount++;
break;
}
The switch Statement
• A switch statement can have an optional
default case
• The default case has no associated value and
simply uses the reserved word default
• If the default case is present, control will transfer
to it if no other case value matches
• If there is no default case, and no other value
matches, control falls through to the statement
after the switch
Switch Statement
tru
variable e
equals first case body
const 1

fals
e
tru
variable e second case body
equals
const 2

fals default body


e
exit
Switch Statement
char c;
printf(”Enter your choice (a/b/c) : ”);
scanf(”%c”,&c);
switch (c)
{
case ’a’:
printf(”You picked a!\n”);
break;
case ’b’:
printf(”You picked b!\n”);
break;
case ’c’:
printf(”You picked c!\n”);
break;
default:
printf(”You picked neither a,b,c !\n”);
}
Repetition Statement
• A repetition statement allows you to specify
that an action is to be repeated while some
condition remains true.

• While there are more items on my shopping list


Purchase next item and cross it off my list
Loops
• The main idea of a loop is to repeat an action or a series of actions.

The concept of a loop


Loops
• But, when to stop looping?
• In the following flowchart, the action is executed over and over again. It
never stop – This is called an infinite loop
• Solution – put a condition to tell the loop either continue looping or
stop.
Loops
• A loop has two parts – body and
condition

• Body – a statement or a block of


statements that will be repeated.

• Condition – is used to control the


iteration – either to continue or stop
iterating.
Loop statements
• C provides three loop statements:
The while Statement in C
• The syntax of while statement in C:
while (loop repetition condition)
statement;
• Loop repetition condition is the condition
which controls the loop.
• The statement is repeated as long as the loop
repetition condition is true.
• A loop is called an infinite loop if the loop
repetition condition is always true.
while statement
while flowchart

while(Condition)
{
Statements;
}
while statement
Example: This while statement prints numbers 10 down to 1
Note that, the first line (n=10) is
actually not a part of the loop statement.

n=10;
while (n>0)
{
printf(“%d “, n);
n=n-1;
}

Output:
10 9 8 7 6 5 4 3 2 1
The for Statement in C
• The syntax of for statement in C:
for (initialization expression;
loop repetition condition;
update expression)
statement;
• The initialization expression set the initial value of the
loop control variable.
• The loop repetition condition test the value of the
loop control variable.
• The update expression update the loop control
variable.
for statement
for flowchart

for (Initialization; Condition; Updating )


{
Repeated_Actions;
}
for statement
Example: This for statement prints numbers 10 down to 1

for (n=10;n>0;n=n-1)
{
printf(“%d “, n);
}

Output:
10 9 8 7 6 5 4 3 2 1
Nested Loops
• Nested loops consist of an outer loop with one
or more inner loops.
• e.g.,
for (i=1;i<=100;i++){ Outer loop
for(j=1;j<=50;j++){

} Inner loop

}
• The above loop will run for 100*50 iterations.
for vs. while statements

Comparing for and while loops


The do-while Statement in C
• The syntax of do-while statement in C:
do statement while (loop repetition
condition);
• The statement is first executed.
• If the loop repetition condition is true, the
statement is repeated.
• Otherwise, the loop is exited.
do…while statement

do
{
Repeated_Actions;
} while (Condition);

do-while loop is used to ensure that the statements within the


loop are executed at least once.
do…while statement
Example: This do…while statement prints numbers 10 down to 1

Note that, the first line (n=10) is


actually not a part of the loop statement.

n=10;
do
{
printf(“%d “, n);
n=n-1;
} while (n>0);

Output:
10 9 8 7 6 5 4 3 2 1
Loop statements
• If the body part has only one statement, then the bracket symbols, { } may
be omitted.

• Example: These two for statments are equivalent.

for (n=10; n>0; n=n-1) for (n=10; n>0; n=n-1)


{ printf(“%d “, n);
printf(“%d ”, n);
}
Jump statements
• You have learn that, the repetition of a loop is controlled by the loop
condition.
• C provides another way to control the loop, by using jump statements.
• There are four jump statements:
break statement
• It causes a loop to terminate

Example:

for (n=10; n>0; n=n-1) Output:


{ 10 9 8
if (n<8) break;
printf(“%d “, n);
}

Break statement takes the execution control out of the loop. The break
statement, when executed in a while, for, do…while or switch statement,
causes an immediate exit from that statement.
continue statement
• In while and do…while loops, the continue statement transfers the control to the loop
condition.

• In for loop, the continue statement transfers the control to the updating part.

The continue statement


continue statement
Example:

for (n=10; n>0; n=n-1) Output:


{ 10 8 6 4 2
if (n%2==1) continue;
printf(“%d “, n);
}

Continue statement skips the execution of the statements after it and takes the
control to the beginning of the loop.
continue statement
Example:

n = 10; Output:
while (n>0) 10 9 9 9 9 9 …………
{
printf(“%d “, n);
if (n%2==1) continue; The loop then prints number 9
over and over again. It never
n = n –1; stops.
}
Return statement
• Exits the function.
• return exits immediately from the currently
executing function to the calling routine,
optionally returning a value. The syntax is:
• return [expression];
• For example,
int sqr (int x) { return (x*x);}
goto
• Unconditionally transfer control.
• goto may be used for transfering control from
one place to another. The syntax is:
• goto identifier; Control is unconditionally
transferred to the location of a local label
specified by identifier. For example,
• Again:
• ...
• goto Again;
goto statement
• It is used to translate connector symbols – jump to another part inside a program.
• But, it is not recommended to use - it may cause unstructured programs.

Example:

n=10;
A:
printf(“%d “, n);
n = n -1;

if (n>0) goto A;

Output:
10 9 8 7 6 5 4 3 2 1
String Handling Library
• Functions defined in #include<string.h>
• String handling library provides many useful
functions:
• Manipulate string data(copy and concatenate)
• Comparing strings
• Determine string length
• Search strings
String Manipulation Functions
• List of string manipulation functions
Function prototype Function description
char *strcpy( char *s1, const char *s2 Copies string s2 into array s1.
)
The value of s1 is returned.
char *strncpy( char *s1, const char Copies at most n characters of
*s2, int n )
string s2 into array s1. The
value of s1 is returned.
char *strcat( char *s1, const char *s2 ) Appends string s2 to array s1.
The first character of s2
overwrites the terminating
null character of s1. The value
of s1 is returned.
char *strncat( char *s1, const char Appends at most n characters
*s2, int n )
of string s2 to array s1. The
strcpy() and strncpy()
• strcpy() copies the entire second argument
string into first argument.
• strcpy( s1, s2);
• strncpy() copies the first n characters of second
string argument into first string argument.
• strncpy( s1, s2, 4);
• A null character ('\0') is appended explicitly to first
argument, because the call to strncpy in the
program does not write a terminating null
character.
• The third argument is less than the string length of
the second argument.
Example Code
This program
demonstrate
s string
manipulation
/ processing
functions:
strcpy() and
strncpy()
Output
The string in array x is: Happy Birthday to You
The string in array y is: Happy Birthday to You
The string in array z is: Happy Birthday
Comparison Functions of the
String Handling Library
• Comparing strings
• Computer compares numeric ASCII codes of
characters in string
• strcmp() Compares its first string argument with its
second string argument, character by character.
• Function strncmp() does not compare characters
following a null character in a string.
strcmp()
int strcmp( const char *s1, const char *s2 );

• Compares string s1 to s2
• Returns
• a negative number if s1 < s2,
• zero if s1 == s2
• a positive number if s1 > s2
strncmp()
int strncmp( const char *s1, const char *s2, int n);

• Compares up to n characters of string s1 to s2


• a negative number if s1 < s2,
• zero if s1 == s2
• a positive number if s1 > s2
Determining the length of string
strlen()
•Function strlen in #include<string.h>

•Function strlen() takes a string as an

argument and returns the number of


characters in the string
• the terminating null character is not included in
the length
Formatted and Unformatted Input/Output
Functions
Outline
• Unformatted Input/Output functions
• getchar()
• putchar()
• getch()
• putch()
• gets()
• puts()
Unformatted Functions
• C has three types of I/O functions:
i. Character I/O
ii. String I/O
iii. File I/O
getchar()
• This function reads a character-type data from
standard input.
• It reads one character at a time till the user
presses the enter key.

Example: Syntax
char c; Variable-name =
c = getchar(); getchar();
#include<stdio.h>
void main()
{
char c;
printf(“enter a character”);
c=getchar();
printf(“c = %c ”,c);
}

Enter a character k
c = k
getch() & getche()
• These functions read any alphanumeric character
from the standard input device
• The character entered is not displayed by the getch()
function until enter is pressed
• The getche() accepts and displays the character.
• The getch() accepts but does not display the
character.

Syntax

getche();
#include<stdio.h>
void main()
{
printf(“Enter two alphabets:”);
getche();
getch();
}

Enter two alphabets a


putch()
This function prints any alphanumeric character
taken by the standard input device
Example:
#include<stdio.h>
void main()
{
char ch;
printf(“Press any key to continue”);
ch = getch();
printf(“ you pressed:”);
putch(ch);
}

Press any key to continue


You pressed : e
gets()
String I/O
• This function is used for accepting any string
until enter key is pressed (string will be
covered later)
Syntax
char str[length of string in number];
gets(str);
#include<stdio.h>
void main()
{
char ch[30];
printf(“Enter the string:”);
gets(ch);
printf(“Entered string: %s”, ch);
}

Enter the string: Use of data!


Entered string: Use of data!
puts()
• This function prints the string or character
array. It is opposite to gets()

Syntax
char str[length of string in number];
gets(str);
puts(str);
#include<stdio.h>
void main()
{
char ch[30];
printf(“Enter the string:”);
gets(ch);
puts(“Entered string:”);
puts(ch);
}

Enter the string: puts is in use


Entered string: puts is in use
Introduction
• Arrays
• Collection of related data items of same data
type.
• Static entity – i.e. they remain the same size
throughout program execution
6
0

Arrays Name of array (Note


that all elements of this
array have the same
name, c)
• Array
• Group of consecutive memory
locations c[ -4
• Same name and data type 0]
c[ 5
1]
c[
• To refer to an element, specify: 2]
c[ 72
• Array name 3]
c[ 3
• Position number in square brackets([]) 4]
c[ -8
• Format: 5]
c[6] 9
c[ 62
• arrayname[position_number] 7]
c[ -3
• First element is always at position 0 8]
c[ 1
• Eg. n element array named c: 9]
c[10] 64
c[0], c[1]...c[n – 1]

c[11] 5378

Position number of the


element within array c
c

Arrays
• An array is an ordered list of values
The entire array Each value has a numeric index
has a single name

c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8]


c[9]
79 87 94 82 67 98 87 81 74
91

An array of size N is indexed from zero to


N-1
This array holds 10 values that are indexed from 0 to 9
Arrays
• Array elements are like normal variables
• c[0] = 3;/*stores 3 to c[0] element*/
• scanf (“%d”, &c[1]);/*reads c[1] element*/
• printf (“%d, %d”, c[0], c[1]);
/*displays c[0] & c[1] element*/
• The position number inside square brackets is called
subscript/index.
• Subscript must be integer or an integer expression
• c[5 - 2] = 7; (i.e. c[3] = 7)
Defining Arrays
• When defining arrays, specify:
• Name
• Data Type of array
• Number of elements
• datatype
arrayName[numberOfElements];
• Examples:
• int students[10];
• float myArray[3284];
• Defining multiple arrays of same data type
• Format is similar to regular variables
• Example:
• int b[100], x[27];
Initializing Arrays
• Initializers
Quick yak:
• int n[5] = { 1, 2, 3, 4, Probe
5 on};the example

below
If not enough initializers given, ask what
then rightmost
happens:
elements become 0 • for (i=1;i<5;i++)
• int n[5] = { 0 }; // initialize

all elements to
for (i=0;i<5;i+=2)

0
• C arrays have no bounds checking.
• If size is omitted, initializers determine it
• int n[] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array.
Initializing Arrays
• Array is same as the variable can prompt for
value from the user at run time.
• Array is a group of elements so we use for
loop to get the values of every element
instead of getting single value at a time.
• Example: int array[5], i; // array of size 5
for(i=0;i<5;i++){// loop begins from 0 to 4
scanf(“%d”, &array[i]);
}
Program of
Initializing an
array to zero
using loop.
0

Element Value
0 0
1 0
2 0
3 0
4 0
5 0 n[ 0
6 0 0]
n[
7 0 1]
n[
8 0 2]
n[ 0
9 0 3]
n[ 0
4]
n[
5]
n[6]
n[ 0
7]
n[ 0
8]
n[ 0
9]
Character Arrays
• Character arrays
• Character arrays can be initialized using string literals
• char string1[] = "first";
•It is equivalent to
• char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };
• Null character '\0' terminates strings
• string1 actually has 6 elements
• Can access individual characters
• string1[ 3 ] is character ‘s’
• Array name is address of array, so & not needed for scanf
scanf( "%s", string2 );

• Reads characters until whitespace encountered


Passing Arrays to Function
• Arrays can be passed to functions in two
ways:
1. Pass entire array
2. Pass array element by element
Pass entire array
• Here entire array can be passed as an argument
to the function
• Function gets complete access to the original
array
• While passing entire array Address of first
element is passed to function, any changes made
inside function, directly affects the Original
value.
void modifyArray(int b[], int arraySize);
• Function passing method: “ Pass by Address”
Pass array element by element
• Here individual elements are passed to the
function as argument
• Duplicate carbon copy of Original variable is
passed to function
• So any changes made inside function does not
affects the original value
• Function doesn’t get complete access to the
original array element.
void modifyElement(int e);
• Function passing method: “ Pass by Value”
Passing Arrays to Functions
• Function prototype
void modifyArray(int b[], int arraySize);
• Parameter names optional in prototype
• int b[] could be written int []
• int arraySize could be simply int
• void modifyArray(int [], int);
• Function call
int a[SIZE];
modifyArray(a, SIZE);
Outline
• Defining and processing
• 1D array
• 2D array
• Applications of arrays
1-D array
• A single- dimensional or 1-D array consists of
a fixed number of elements of the same data
type organized as a single linear sequence.
• The elements of a single dimensional array
can be accessed by using a single subscript
• The arrays we have studied till now were 1D
array or linear array.
• Example: int a[n];
#include<stdio.h>
void main()
Program to
{ display the
int avg, sum=0, i; average of
int marks[30];
for(i=0;i<=29;i++)
/*array declaration*/
elements in 1D
{ array
printf(“enter numbers”);
scanf(“%d”,&marks[i]); /*store data in
array*/
}
for(i=0;i<=29;i++)
{
sum = sum + marks[i]; /*read data from an
array*/
}
avg = sum/30;
printf(“Average marks= %d”, avg);
}
Multiple-Subscripted Arrays
• Multiple subscripted arrays
• Tables with rows and columns (m by n array)
• Like matrices: specify row, then column
• int a[rows][column];

Colum Colum Column 2 Colum


n 00 ][0 0 ]
a[ n 01 ][ 1 ]
a[ a[ 0 ][ 2 ] n0
a[ 3 ][ 3 ]
Ro
w
Ro a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
0
w
Ro a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
1
w
2
Column subscript
Array name
Row subscript
Operations on arrays
• Insertion of element into an array
• Deletion of element from an array
#include <stdio.h>
#include <conio.h> Program to
int main() insert an
{
int array[100], position, c, n, value;
element into an
printf("Enter number of elements in
array:\n");
array
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (c = 0; c < n; c++)
{ scanf("%d", &array[c]); }
printf("Enter the location where you wish to
insert an element:\n");
scanf("%d", &position);
printf("Enter the value to insert:\n");
scanf("%d", &value);
for (c = n - 1; c >= position - 1; c--)
{ array[c+1] = array[c]; }
array[position-1] = value;
printf("Resultant array is:\n");
for (c = 0; c <= n; c++)
{ printf("%d\n", array[c]); }
}
Enter number of elements in array: 4
Enter 4 elements
2
45
66
33
Enter the location where you wish to insert
an element : 2
Enter the value to insert : 99
Resultant array is :
2
99
45
66
33
#include <stdio.h>
int main() Program to
{ delete an
int array[100], position, c, n;
printf("Enter number of elements in element from
array\n"); an array
scanf("%d", &n);
printf("Enter %d elements\n", n);
for (c = 0; c < n; c++)
{ scanf("%d", &array[c]); }
printf("Enter the location where you wish
to delete from an array\n");
scanf("%d", &position);
for (c = position-1; c < n; c++)
{ array[c] = array[c+1]; }

printf("Resultant array is\n");


for (c = 0; c < n-1; c++)
{ printf("%d\n", array[c]); }
}
Enter number of elements in array: 4
Enter 4 elements
2
45
66
33
Enter the location where you wish to to
delete from an array : 2
Resultant array is :
2
66
33
Application Of Array :
Stores Elements of Same Data Type
• Array is used to store the number of elements that are of same data
type.
• Eg: int students[30];
• array of marks of five subjects for single student.
float marks[5];
• array of marks of five subjects for 30 students.
float marks[30][5]
• Similarly if we declare the character array then it can hold only
character.
• So in short character array can store character variables while floating
array stores only floating numbers.
Array Used for Maintaining multiple variable names using single
name
Suppose we need to store 5 roll numbers of students then without
declaration of array we need to declare following -
int roll1,roll2,roll3,roll4,roll5;
1.Now in order to get roll number of first student we need to access
roll1.
2.Guess if we need to store roll numbers of 100 students then what
will be the procedure.
3.Maintaining all the variables and remembering all these things is
very difficult.
•So we are using array which can store multiple values and we have
to remember just single variable name.
Array Can be Used for Sorting Elements
• We can store elements to be sorted in an array and then by
using different sorting technique we can sort the elements.
Different Sorting Techniques are :
1. Bubble Sort
2. Insertion Sort
3. Selection Sort
Array Can Perform Matrix Operation
Matrix operations can be performed using the array. We can
use 2-D array
•To store the matrix.

•To perform all mathematical manipulations on matrix.

•Matrix can be multi-dimensional.


Some classic daily examples…
• 1D
• Running
• Distance [D]

• 2D
• Long Jump
• Distance, Height [D,H]

• 3D
• High Jump
• Distance, Height, Roll [D,H,R]
Pointers
• A variable which stores address of another
variable
• Example:
int *p;
int i;
p= &i;
• *p gives value at address stored in p.
• int *p means p is containing an address of
variable on which an integer is stored
Calling Functions by Reference
• Call by reference with pointer arguments
• Pass address of argument using & operator
• Allows you to change actual location in memory
• * operator
• Used as alias/nickname for variable inside of function
• void double( int *number )
• {
• *number = 2 * ( *number );
• }
• *number used as nickname for the variable passed
#include <stdio.h>
void cubeByReference(int *nPtr); //function prototype
int main( void )
{
int number = 5;
printf("The original value of number is %d", number);
cubeByReference( &number ); //pass address of number
printf("\nThe new value of number is %d\n", number);
} // end main

//calculate cube of *nPtr; actually modifies number in main


void cubeByReference( int *nPtr )
{
*nPtr = *nPtr * *nPtr * *nPtr; //cube *nPtr
}z

The original value of number is 5


The new value of number is 125
Outline
• Declaration of a structure
• Definition and initialization of structures.
• Accessing structures.
Introduction
• Structures are derived data types—they are
constructed using objects of other types.
• Structures
• Structure is a group of data items of different data
types held together in a single unit.
• Collections of related variables under one name
• Can contain variables of different data types
• Commonly used to define records to be stored in
files.
Why Use Structures?
• Quite often we deal with entities that are collection of
dissimilar data types.
• For example, suppose you want to store data about a
car. You might want to store its name (a string), its
price (a float) and number of seats in it (an int).
• If data about say 3 such cars is to be stored, then we
can follow two approaches:
• Construct individual arrays, one for storing names, another
for storing prices and still another for storing number of
seats.
• Use a structure variable.
Structure
• There are three aspects of working with
structures:
• Defining a structure type
• Declaring variables and constants of newly
created type
• Using and performing operations on the objects
of structure type
Structure Definition

struct sname {
type var1;
type var2;
type var3;
.
.
type varN;
};

struct is a keyword to define a structure.


sname is the name given to the structure/structure
tag.
type is a built-in data type.
var1,var2,var3,…..,varN are elements of structure
being defined.
; semicolon at the end.
Structure Definitions
• Example:

• struct car{
• char *name;
• int seats;
• float price };
• struct keyword introduces the definition for structure car
• car is the structure name or tag and is used to declare variables of
the structure type
• car contains three members of type char, float, int
• These members are name, price and seats.

• No variable has been associated with this structure


• No memory is set aside for this structure.
Structure Definitions
• struct information
• A structure definition does not reserve space in memory .
• Instead creates a new data type used to define structure variables
• Defining variables of structure type
• Defined like other variables:
• Car myCar, cars[5], *cPtr;
• Can use a comma separated list along with structure definition:
• struct car{
• char *name;
• int seats;
• float price; } myCar, cars[5], *cPtr;
At this point, the memory is set aside for the structure
variable myCar.
How the members are stored in
memory
Consider the declarations to understand how the
members of the structure variables are stored in
memory
struct car{
char *name;
int seats;
float price; }myCar,
Note: all members are stored in contiguous memory location in order in which they are
declared.
How the members of the structure variables are
stored in memory
1197
1198
name 1199
1200
1201
seat 1202
s 1203
1204
1205
pric 1206
e
1207
1208
1209
1210
1211
Structure Definitions
• Operations that can be performed on
structures
• Assigning a structure to a structure of the same
type
• Taking the address (&) of a structure
• Accessing the members of a structure
• Using the sizeof operator to determine the size of a
structure
Initializing Structures
• Initializer list
• To initialize a structure similarly like arrays
• Example:
• car myCar = { “Renault", 500000, 2 };
• Could also define and initialize myCar as follows:
• Car myCar;
• myCar.name = “Renault”;
• myCar.price = 500000;
• myCar.seats = 2;
Accessing Members of Structures
• Two operators are used to access members
of Structures:
• Dot operator (.) used with structure variables
• car myCar;
• Printf("%d", myCar.seats);
• Arrow operator (->) used with pointers to
structure variables
• car *myCarPtr = &myCar;
• printf("%d", myCarPtr->seats);
• myCarPtr->name is equivalent to
• (*myCarPtr).seats
dot Operator
• Members are accessed using dot operator.
• It provides a powerful and clear way to refer to
an individual element.
• Syntax: sname.vname
• sname is structure variable name.
• vname is name of the element of the structure.
• Eg: the members of the structure variable car can
be accessed as
myCar.name, myCar.seats, myCar.price
Use of Assignment Statement for
Structures
• The main advantage of structure is that it can be
treated as single entity.
• The only legal operations that can be performed on
structure are copying to it as a single unit using the
assignment operator.
• Value of one structure variable can be assigned to
another variable of the same type using simple
assignment statement.
• If myCar and newCar are structure variable of
type car, then
newCar = myCar;
Use of Assignment Statement for
Structures
• When we assigns value of structure variable myCar to
newCar, all values of members of one structure get
copied into corresponding members of another
structure.
• Or we can copy one member at a time:
• newCar.name = myCar.name;
• Simple assignment cannot be used this way for
arrays.
• This is really a big advantage over arrays where in
order to copy one array into another of same type, we
have copied the contents element by element either
using loop or individually.
#include <stdio.h>
struct car{
Program to
char *name; show how to
int seats; access
float price; structure.
}; //end structure car

int main()
{
struct car myCar; //define struct variable
myCar.name = “Renault";
myCar.price = 500000;
myCar.seats = 2;
printf("%s %f %d \n”, myCar.name,
myCar.price, myCar.seats);
} //end main

Renault 500000 2
#include <stdio.h>
struct car{ Program to
char name[50]; enter data into
int seats;
float price;
structure.
};
main()
{
struct car myCar;
printf(“Enter name of car:\n”);
gets(myCar.name);
printf(“Enter number of seats in car:\n”);
scanf(“%d”, &myCar.seats);
printf(“Enter price of car:\n”);
scanf(“%f”, &myCar.price);
printf(“\n\nParticulars of car are:\n”);
printf(“Car name:%s”,myCar.name);
printf(“\nNumber of seats:%d”,
myCar.seats);
printf(“\nPrice:%f”, myCar.price);
} //end main
Enter name of car: Micra
Enter number of seats in car: 4
Enter price of car: 600000

Particulars of car are:


Car name: Micra
Number of seats: 4
Price: 600000
Array & Structure
Array Structure

1. It is a collection of data items of same 1. It is a collection of data items of


data type. different data types.

2. It has declaration only. 2. It has declaration & definition.

3. There is no keyword. 3. struct is the keyword.

4. An array name represents the address of 4. A structure name is called tag. It is a


the starting element. short hand notation of the declaration.

5. An array cannot have bit fields. 5. It may contain bit fields.


Nested Structure
• Nested structures are structures as member
of another structure.
• We can also take objects of one structure as
member in another structure.
• Thus, a structure within a structure can be
used to create complex data application.
• Dot operator is used twice because we are
accessing first structure through the object of
second structure.
Nested Structure
Two ways of declaring structure within
structure or Nested structure:
•Declare two separate structures

•Embedded structures
Example
struct Date
{
int dd;
int mm;
int yy;
};
struct Student
{
char name[20];
int rollno;
int marks;
struct Date dob;
};
Here structure Student is nesting structure and structure date is nested structure
Example: embedded structures
struct Student
{
char name[20];
int rollno;
struct date
{
int dd;
int mm;
int yy;
} dob;
};
#include<stdio.h>
void main() WAP to read
{
struct time{
and display the
int second; car number,
int minute;
int hour; starting time
};
struct car and reaching
{
int carno;
time using
struct time st; structure within
};
structure.
struct car myCar;
printf(“\n car no. starting time reaching
time:”);
scanf(“%d”, &myCar.carno);
scanf(“%d %d %d”, & myCar.st.hour,
&myCar.st.minute, &myCar.st.second);
printf(“\n%d”, myCar.carno);
printf(“\t %d:%d:%d \t” myCar.st.hour,
myCar.st.minute, myCar.st.second);
}
Unions
• union
• Memory that contains a variety of objects over time
• Only contains one data member at a time
• Members of a union share space
• Conserves storage
• Only the last data member defined can be accessed
• union definitions
• Same as struct
• union Number {
• int x;
• float y;
• };
• union Number value;
Union
• Union is similar as structure. The major
distinction between them is in terms of
storage.
• In structure each member has its own storage
location whereas all the members of union
uses the same location.
• The union may contain many members of
different data type but it can handle only one
member at a time union can be declared using
the keyword union.
Union Declaration
union item
{
int m;
float x;
char c;
}code;
This declare a variable code of type union item
Unions
• Valid union operations
• Assignment to union of same type: =
• Taking address: &
• Accessing union members: .
• Accessing members using pointers: ->
#include <stdio.h>
union job{
Program using
char name[32]; union.
float salary;
int worker_no;
}u;
main()
{
printf("Enter name:\n");
scanf("%s",&u.name);
printf("Enter salary: \n");
scanf("%f",&u.salary);
printf("Displaying\nName :%s\n",u.name);
printf("Salary: %.1f",u.salary);
}
Enter name Hillary
Enter salary 1234.23
Displaying
Name: f%Bary
Salary: 1234.2

Initially, Hillary will be stored in u.name and other


members of union will contain garbage value. But when user
enters value of salary, 1234.23 will be stored in u.salary and
other members will contain garbage value. Thus in output,
salary is printed accurately but, name displays some random
string.
Outline
• Passing structure to a function
• Pointers to the structure.
Structure and Function
• The relationship of structure with the function
can be viewed from three angles:-

1. Passing Structures to a function.


2. Function Returning Structure.
3. Passing array of Structures to Function.
• Passing multiple arguments in and out of
functions through a single argument
Passing Structures to Functions
• Passing structures to functions
• Pass entire structure
• Or, pass individual members
• Both are pass by value.
• To pass structures call-by-reference
• Pass its address
• To pass arrays by value
• Create a structure with the array as a member
• And pass that structure.
Passing Structure to a Function
Similar to passing array of variable, structure can
be passed to a function as argument

type-specifier func-name(struct-variable);
#include <stdio.h>
struct car{
Passing of
char name[50]; structure to a
int seats; function by
float price;
}; value
void cardata(struct car); /*function
prototype*/
void main()
{
struct car myCar = {“Racer”, 1, 1200000};
cardata(myCar); //function calling
}
void cardata(struct car newCar)
{
printf(“\nData about your car is: %s %d %f”,
newCar.name, newCar.seats, newCar.price);
}

Data about your car is Racer 1 1200000


#include <stdio.h>
struct car{ Passing of
char name[50]; structure
int seats;
float price; member to a
}; function by
void cardata(struct car); /*function
prototype*/ value.
void main()
{
struct car myCar = {“Racer”, 1, 1200000};
cardata(myCar); //function calling
printf(“\nData about your car is: %s %d %f”,
myCar.name, myCar.seats, myCar.price);
}
void cardata(struct car newCar)
{
newCar.seats = 2; /*changing the number of
seats*/
}

Data about your car is Racer 1 1200000


#include <stdio.h>
struct car{ Passing of
char name[50];
int seats;
structure by
float price; reference to a
};
void cardata(struct car*); /*function function
prototype*/
void main()
{
struct car myCar;
printf(“Enter data:\n”);
cardata(&myCar);
printf(“\nData about your car is: %s %d %f”,
myCar.name, myCar.seats, myCar.price);
}
void cardata(struct car *newCar)
{
gets(newCar->name);
scanf(“%d %f”, &newCar->seats, &newCar->price);
}

Enter data: Racer 1 1200000


Data about your car is Racer 1 1200000
#include <stdio.h>
struct car{ Passing of
char name[50];
int seats; structure by
};
float price; reference to a
void cardata(struct car*); /*function
prototype*/
function
void main()
{
struct car myCar= {"Racer", 1, 1200000};
printf("\nData about your car is: %s %d %f",
myCar.name, myCar.seats, myCar.price);
cardata(&myCar);
printf("\nData about your car is: %s %d %f",
myCar.name, myCar.seats, myCar.price);
}
void cardata(struct car *newCar)
{
struct car c = {“Safari", 4, 899000};
*newCar= c; /*the value of c is copied at
location pointed by newCar*/
}

Data about your car is Racer 1 1200000


Data about your car is Safari 4 899000
Array of Structures
• to store data of 100 cars we would be
required to use 100 different structure
variables from car1 to car100, which is
definitely not very convenient. A better
approach would be to use an array of
structures.
struct car mycar[100];
• This provides space in memory for 100
structures of the type struct car.
#include <stdio.h>
struct car{ Program to
char name[50];
int seats;
print array of
float price; structures.
};
void main()
{
int i;
struct car myCar[100];

for(i=0; i<100; i++){


printf(“\n\nEnter data for car[%d]:\n”, i);
scanf(“%s %d %f”, &myCar[i].name,
&myCar[i].seats, &myCar[i].price);
}

for(i=0; i<100; i++){


printf(“\nData about your car[%d] is: %s %d %f”,
i, myCar[i].name, myCar[i].seats,
myCar[i].price);
}
}
Enter data for car0: Racer 1 1200000
Data about your car0 is Racer 1 1200000
Enter data for car1: Micra 4 500000
Data about your car1 is Micra 4 500000
Enter data for car2: RacerGt 1 800000
Data about your car2 is RacerGt 1 800000
.
.
.
.
.
Enter data for car99: RacerEf 1 2000000
Data about your car99 is RacerEf 1 2000000
Accessing Members of Structures
• Arrow operator (->) used with pointers to
structure variables
• car *myCarPtr = &myCar; //intializing pointer
• printf("%s", myCarPtr->name);
• myCarPtr->name is equivalent to
• (*myCarPtr).name
#include <stdio.h>
struct car{ Program for
char *name; pointer to a
int seats;
float price;
structure
};
int main()
{
struct car myCar = {“Renault”,2, 500000};
struct car *myCarPtr; //define a pointer to car
myCarPtr = &myCar; /*assign address of myCar to
myCarPtr */

printf("%s %f %d \n%s %f %d \n%s %f %d\n",


myCar.name, myCar.price, myCar.seats,
myCarPtr->name, myCarPtr->price,
myCarPtr->seats,
(*myCarPtr).name, (*myCarPtr).price,
(*myCarPtr).seats);
} //end main

Renault 500000 2
Renault 500000 2
Renault 500000 2
Concepts and Basics of C++
Programming
Object-Orientation

• A thinking methodology
– Everything is an object.
– Any system is composed of objects (a system
is also an object).
– The evolution and development of a system is
caused by the interactions of the objects
inside/outside a system.
Everything is an object

• A student, a professor
• A desk, a chair, a classroom, a building
• A university, a city, a country
• The world, the universe
• A subject such as CS, IS, Math, History, …
The development of a system is caused by
interactions

• LPU is defined by the interactions


among:
– students
– professors Inside LPU
– staff
– Board governance
– State governance
– … ...
Outside LPU
Reading and Writing Data

• Two operators are introduced in c++ i.e. cout and


cin.
• Cout is a predefined object and represents the
standard output stream and this output stream
represents the screen. Cout, requires iostream file
E.g. cout<<“ I love india”;
cout will display this string as such on screen.
• << is called insertion or put to operator.
• if string is variable then cout can be used
to display the contents of string.
E.g. cout<< string;
• cin is used to read the data.
• cin>>a;
• >> is called extraction operator.
Reading Strings with cin
• Can be used to read in a string
• Must first declare an array to hold characters in
string:
– char myName[21];
• nyName is name of array, 21 is the number of
characters that can be stored (the size of the
array), including the NULL character at the end
• Can be used with cin to assign a value:
– cin >> myName;
Class
• A class is a user defined data type which
holds both data and function.
• The data included in the class i.e the
internal data is called data member and
the functions included is called the
member function.
• These member functions can manipulate
the internal data of the class
Object
• Is an instant of a class.
• In terms of variables, class would be the
type and an object would be a variable.
Creating Classes in C++
• A class definition begins with the
keyword class.
• The body of the class is contained within
a set of braces, { } ; (notice the
semi-colon).

Any valid
identifier

class class_name
{ Class body (data member +
….
…. methods)
….
};
class classname
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
protected:
variable declarations;
function declarations;
} obj1, obj2,…..objN;
Class name
• Name given to a particular class (any user
define name). It can also be called as tag
name of the class that act as the type
specifier for class using which we can
create objects.
• The class is specified by keyword “class”
Data Members
• Data type properties that describe the
characteristics of a class.
• We can declare any number of data
members of any type in a class.
E.g. int x;
Member functions

• Various operations that can be performed


to data members of that class.
• We can declare any number of member
functions of any type in a class.

E.g. void read();


Access Specifiers
• Used to specify access rights for the data
members and member functions of the class.
• Depending upon the access level of a class
member, access to it is allowed or denied.
• Within the body, the keywords private: and
public: specify the access level of the
members of the class.
– the default is private.
• Usually, the data members of a class are
declared in the private: section of the class
and the member functions are in public:
section.
private members or
methods
class class_name
{
private:


… Public members or
public: methods



};
Private:
only members of that class have
accessibility
• can be accessed only through member
functions of that class i.e by the functions
declared inside the class only.

• Private members and methods are for


internal use only.
Public:
• Accessible from both inside and outside the class
also i.e by the functions declared in the main()
program also.
Protected:
• Stage between private and public access.
• They can be accessed by the member function or
friend functions of the class. They are similar to
private members in the sense that they cannot be
accessed by the non- member functions of the class.
Class Example
• This class example shows how we can
encapsulate (gather) a circle information
into one package (unit or class)
No need for others classes to access
and retrieve its value directly. The
class methods are responsible for
that only.

class Circle They are accessible from outside


{ the class, and they can access the
private: member (radius)
double radius;
public:
void setRadius(double r); double
getDiameter();
double getArea();
double getCircumference();
};
Methods definition
• The member function of the class can be defined in two
different ways:
1) Inside the class definition:- The member functions are
simple defined inside the class only i.e the body of the
function resides inside the range of class only.
2) Outside the class definition: by using scope resolution
operator, which specifies that the scope of the function is
restricted to the class class_name.
Syntax:- class_name:: function_name
Inside the class definition
Eg: class abc
{
cout<<“rollno=“;
private:
cin>>rollno;
int rollno;
}
char name[20];
void display()
public:
{
void getdata()
cout<<“name=“<<name;
{
cout<<“rollno=“<<rolln
cout<<“name=“;
o;
cin>>name;
}
};
Outside the class definition
cin>>name;
Eg: class abc
{ cout<<“rollno=“;
private: cin>>rollno;
int rollno; }
char name[20]; void abc :: display()
public: {
void getdata(); cout<<“name and
rollno=“;
void display();
cout<<name<<rollno;
};
}
void abc :: getdata()
{
cout<<“name=“;
INLINE AND NON INLINE MEMBER
FUNCTION
• A function defined inside the class is by
default inline function
• A function defined outside the class using
scope resolution operation is non-inline
function. It can be made inline by using
keyword inline before the function
definition.
Eg. inline void abc::getdata()
Declaring objects
• Defining objects of class data type is
known as class instantiation(instances of
class).
• When we create objects during that
moment , memory is allocated to them.
– Ex- class Circle c;
class book void book ::display()
{ {
private: cout<<“book
int p; char n[40]; name=“<<n;
public: cout<<“book
void getdata() price=“<<p;
{ }
cout<<“enter book void main()
price”; {
cin>>p; class book obj;
cout<<“enter book obj.getdata();
name”; obj.display();
cin>>n; } }
void display(); };
Accessing class members
• Public members of class can be accessed
using dot(.) operator with the object
name.
• Private members of the class are accessed
inside the public member functions of
class.

Eg: obj.getdata();
Access privileges in C++.

You have access privileges in C++ such as


public, protected and private that helps in
encapsulation of data at various level.
Private
If data are declared as private in a class then
it is accessible by the member functions of the
class where they are declared. The private
member functions can be accessed only by the
members of the class. By default, any member
of the class is considered as private by the C++
compiler, if no specifier is declared for the
member.
Public The member functions with public
access specifier can be accessed outside of
the class. This kind of members is accessed by
creating instance of the cass.
• Protected Protected members are accessible by
the class itself and it's sub-classes. The
members with protected specifier act exactly
like private as long as they are referenced
within the class or from the instance of the
class. This specifier specially used when you
need to use inheritance facility of C++. The
protected members become private of a child
class in case of private inheritance, public in
case of public inheritance, and stay protected in
case of protected inheritance.
• When we want our private data to be shared
by a non member function
Then
• Basically, we declare something as a friend,
you give it access to your private data
members.
• Single functions or entire classes may be
declared as friends of a class.
Friend function
• A Friend function is a non-member function of the
class that has been granted access to all private
members of the class.

• We simply declare the function within the class by a


prefixing its declaration with keyword friend.

• Function definition must not use keyword friend.

• Definition of friend function is specified outside the


class body and is not treated as a part of the class.

• The major difference b/w member function and friend


function is that the member function is accessed
through the object while friend function requires
object to be passed as parameter.
Syntax:
class ABC
{
………….
public:
friend void xyz(object of class);
};
Friend function characterstics

• It is not in scope of class.


• It cannot be called using object of that class.
• It can be invoked like a normal function.
• It should use a dot operator for accessing
members.
• It can be public or private.
• It has objects as arguments.
• Perhaps the most common use of friend functions
is overloading << and >> for I/O.
Friend Function definedinside the
class
Class demo
{
Private:
Int a;
Public:
Void getdata();
Friend void sample(demo abc)
{
Cout<<abc.a;
}
};
Example

class demo
{
int x;
public:
demo(int a)
{
x=a;
}
friend void display(demo);
};
void display(demo d1)
{
cout<<d1.x;
}
void main()
{
demo d2(5);
display(d2);
}
• class sample
{
int a;
int b;
public:
void setval(){ a=25,b=40}
friend float mean(sample s);
};
float mean(sample s)
{ return (s.a+s.b)/2.0;
}
void main()
{ sample X;
X.setval();
cout<<mean(X);
}
Friend class

• In previous section of class we declared only


one function as a friend of another class. but it
is possible that all member of the one class
can be friend of another class. This is friend
class.
What is function????
• Function is a self contained block of
statements that perform a coherent task
of some kind.
• Every C++ program can be a thought of
the collection of functions.
• main( ) is also a function.
Types of Functions.

• Library functions
• User defined functions.
– Programmer can create their own function in
C++ to perform specific task
Why use function?
• Writing functions avoids rewriting of the
same code again and again in the
program.
• Using function large programs can be
reduced to smaller ones. It is easy to
debug and find out the errors in it.
• Using a function it becomes easier to
write program to keep track of what they
are doing.
//Function Declaration retn_type func_name(data_type
1,data_type );
//Function Definition
rent_type func_name(data_type par1,data_type
par2)
{
// body of the function
}
//Function Call
func_name(par1,par2);
Function prototype
• A prototype statement helps the
compiler to check the return type and
arguments type of the function.
• A prototype function consist of the
functions return type, name and
argument list.
• Example
– int sum( int x, int y);
Example
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
void sum(int, int); // function declaration
int a, b;
cout<<“enter the two no”;
cin>>a>>b;
sum(a,b); // function calling
getch();
}
void sum( int x, int y) // function definition
{
int c=x+y;
cout<< “ sum is”<<c;
}
#include<conio.h>
main()
{
int a=10,b=20;
int sum(int, int);
int c=sum(a,b); //actual arguments
Cout<<“sum is” << c;
getch();
}
int sum(int x, int y) //formal arguments
{
int s;
s=x+y;
return(s); //return value
}
Categories of functions

• A function with no parameter and no


return value
• A function with parameter and no return
value
• A function with parameter and return
value
• A function without parameter and return
value
A function with no parameter and no return value
#include<conio.h>
void main()
{
void print(); /*func declaration
Cout<<“no parameter and no return value”;
print(); /*func calling
getch();
}
void print() /*func definition
{
For(int i=1;i<=30;i++)
{
cout<<“*”;
}
Cout<<“\n”;
}
A function with no parameter and no return value

• There is no data transfer between calling


and called function
• The function is only executed and
nothing is obtained
• Such functions may be used to print
some messages, draw stars etc
A function with parameter and no return
value

#include<conio.h>
void main()
{
clrscr();
int a=10,b=20;
void mul(int,int);
mul(a,b); /*actual arguments
getch();
}
void mul(int x, int y) /*formal arguments
{
int s;
s=x*y;
Cout<<“mul is” << s;
}
A function with parameter and return value

#include<conio.h>
void main()
{
int a=10,b=20,c;
int max(int,int);
c=max(a,b);
Cout<<“greatest no is” <<c;
getch();
}
int max(int x, int y)
{
if(x>y)
return(x);
else
{
return(y);
}
}
A function without parameter and return
value
#include<conio.h>
void main()
{
clrscr();
int a=10,b=20;
int sum();
int c=sum(); /*actual arguments
Cout<<“sum is”<< c;
getch();
}
int sum() /*formal arguments
{
int x=10,y=20;
return(x+y); /*return value
}
Default arguments
• In the function prototype (declaration) ,
the default values are given. Whenever a
call is made to function without
specifying an argument , the program
will automatically assign values to the
parameters from the default function
prototype.
• Default arguments facilitate easy
development and maintenance of
programs.
#include<iostream.h>
void main()
{
void sum(int x=10, int y=20);
sum();
}

void sum(int a1,int a2)


{
Int temp;
temp= a1+a2;
Cout<<“Sum is”<<temp;
}
Inline Functions

• Each time you call a function in a C++ program, the


computer must do the following:
– Remember where to return when the function eventually ends
– Provide memory for the function’s variables
– Provide memory for any value returned by the function
– Pass control to the function
– Pass control back to the calling program
• This extra activity constitutes the overhead, or cost of
doing business, involved in calling a function
Inline Functions

• An inline function is a small function with no calling


overhead
• Overhead is avoided because program control never
transfers to the function
• A copy of the function statements is placed directly
into the compiled calling program
• The inline function appears prior to the main(), which
calls it
• Any inline function must precede any function that
calls it, which eliminates the need for prototyping in
the calling function
Inline Functions

• When you compile a program, the code for the inline


function is placed directly within the main() function
• You should use an inline function only in the following
situations:
– When you want to group statements together so that you can
use a function name
– When the number of statements is small (one or two lines in
the body of the function)
– When the function is called on few occasions
Inline functions
• One of the objectives of using functions
is to save some memory space, which
becomes appreciable when a function is
likely to be called many times.
• Every time a function is called , it takes a
lot of extra time in executing a series of
instructions.
• To eliminate the cost of calls to small
functions , C++ proposes inline function.
• An inline function is a function that
expanded in line when it is invoked.
• The compiler replaces the function call
with corresponding function code.
• inline function header
{
function body
}
Prefix the keyword inline to the function definition.
#include<iostream.h>
inline float mul(float x, float y)
{
return(x*y);
}
Inline double div(double p, double q)
{
return(p/q);
}
void main()
{
float a = 12.345;
float b = 9.82;
cout<< mul(a,b) << “\n”;
cout<<div( a,b)<< “\n”
}
SCOPE RULES
• Local Variable
• Global variable
• Local Variables are defined inside the
function body or in a compound statement.
The scope of these variables are inside the
function where they are defined.
Eg: int fact (int n)
{
Int i, fact, j; // i, j are local variables.
-----
----
}
• Global variables are those variables
whose scope is available through out the
program.
Argument passing techniques
• Pass By Value
• Pass By Pointer/Address
• Pass By Reference
Call By Value
• It is a default mechanism for argument
passing.
• Any changes made in the formal
argument are not reflected back to
actual argument, rather they remain
local to the block which are lost once the
control is returned back to calling
program
EXAMPLE
void main()
{
int a=10,b=20;
void swap(int,int);
Cout<<“before function calling”<<a<<b;
swap(a,b);
Cout<<“after function calling”<<a<<b;
getch();
}
void swap(int x,int y)
{
int z;
z=x;
x=y;
y=z;
Cout<<“value is”<<x<<y;
}
Output:
before function calling a=10 b=20
value of x=20 and y= 10
after function calling a=10 b=20
Call By pointer/address
• In this instead of passing value, address
are passed.
• Here formal arguments are pointers to
the actual arguments
• Hence change made in the argument are
permanent.
Void main()
{
int a=10 ,b=25;
void swap(int *,int *);
Cout<<“before function calling”<<a<<b;
swap(&a,&b);
Cout<<“after function calling”<<a<<b;
getch();
}
void swap(int *x,int *y)
{
int z;
z=*x;
*x=*y;
*y=z;
Cout<<“value is”<<*x<<*y;
}
Output:
before function calling a= 10 b= 25
value of x=25 and y=10
after function calling a=25 b= 10
Call By Reference(Using Reference Variables
with Functions)

• To create a second name for a variable


in a program, you can generate an alias,
or an alternate name

• In C++ a variable that acts as an alias for


another variable is called a reference
variable, or simply a reference
Declaring Reference Variables

• You declare a reference variable by placing


a type and an ampersand in front of a
variable name, as in double &cash;
and assigning another variable of the same
type to the reference variable
– double someMoney;
– double &cash = someMoney;

• A reference variable refers to the same


memory address as does a variable, and a
pointer holds the memory address of a
variable
EXAMPLE REFERENCE VARIABLE
void main()
{
int i=10;
int &j=i; // j is a reference variable of I
cout<<“value”<<i<<“\t”<<j;
j=20;
cout<<“modified value”<<i<<“\t”<<j;
getch();
}
Output:-
Value 10 10
modified value 20 20
PASS BY REFERENCE
Void main()
{
int a=10 ,b=25;
void swap(int &a, int &b);
cout<<“before function calling”<<a<<b;
swap(a, b);
cout<<“after function calling”<<a<<b;
getch();
}
void swap(int &x, int &y)
{
int z;
z=x;
x=y;
y=z;
cout<<“value is”<<x<<y;
}
Output:
before function calling a= 10 b= 25
value of x=25 and y=10
after function calling a=25 b= 10
Recursion
• When function call itself repeatedly ,until
some specified condition is met then this
process is called recursion.
• It is useful for writing repetitive problems
where each action is stated in terms of
previous result.
• The need of recursion arises if logic of the
problem is such that the solution of the
problem depends upon the repetition of
certain set of statements with different
input values an with a condition.
(EXAMPLE)Factorial using recursion

void main() int fac(int a)


{ {
int fac(int); int b;
int n, fact; if(a<=1)
cout<<“enter the no.”; {
cin>>n; return(1);
fact=fac(n); }
cout<<“factorial else
is”<<fact; {
getch(); b=a*fac(a-1);
} return(b);
}}
Advantages of recursion
1. It make program code compact which is
easier to write and understand.
2. It is used with the data structures such as
linklist, stack, queues etc.
3. It is useful if a solution to a problem is in
repetitive form.
4. The compact code in a recursion
simplifies the compilation as less number
of lines need to be compiled.
Disadvantages
1. Consume more storage space as
recursion calls and automatic variables
are stored in a stack.
2. It is less efficient in comparison to
normal program in case of speed and
execution time
3. Special care need to be taken for
stopping condition in a recursion
function
4. If the recursion calls are not checked ,the
computer may run out of memory.
FUNCTION
OVERLOADING
Polymorphism
• The word polymorphism is derived from
Greek word Poly which means many and
morphos which means forms.
• Polymorphism can be defined as the
ability to use the same name for two or
more related but technically different
tasks.
• Eg-woman plays role of daughter, sister,
wife, mother, etc.
Overloading in C++
• What is overloading
– Overloading means assigning multiple
meanings to a function name or operator
symbol
– It allows multiple definitions of a function
with the same name, but different
signatures.
• C++ supports
– Function overloading
– Operator overloading
Why is Overloading Useful?
• Function overloading allows functions
that
conceptually perform the same task on
objects of different types to be given the
same name.
• Operator overloading provides a
convenient
notation for manipulating user-defined
objects with conventional operators.
Function Overloading
• Is the process of using the same name
for two or more functions
• Requires each redefinition of a function
to use a different function signature that
is:
– different types of parameters,
– or sequence of parameters,
– or number of parameters
• Is used so that a programmer does not
have to remember multiple function
names
Function Overloading
• Two or more functions
can have the same name
but different parameters
Example:
int max(int a, int b) float max(float a, float
{ b)
–if (a>= b) {
– return a; – if (a>= b)
– else – return a;
– return b; – else
} – return b;
}
Function with Default arguments
• In the function prototype (declaration) , the
default values are given. Whenever a call is
made to function without specifying an
argument , the program will automatically
assign values to the parameters from the
default function prototype.
• Default arguments facilitate easy development
and maintenance of programs.
#include<iostream.h>
void sum(int x=10, int y=20);
void main()
{
sum();
}
void sum(int a1,int a2)
{
int temp;
temp= a1+a2;
cout<<“Sum is”<<temp;
}
Streams
• Stream
– A transfer of information in the form of a sequence
of bytes

• I/O Operations:
– Input: A stream that flows from an input device (
i.e.: keyboard, disk drive, network connection) to
main memory
– Output: A stream that flows from main memory to
an output device ( i.e.: screen, printer, disk drive,
network connection)
Iostream Library Header Files

• iostream library:
– <iostream.h>: Contains cin, cout, cerr, and clog
objects
– <iomanip.h>: Contains parameterized stream
manipulators
– <fstream.h>: Contains information important to
user-controlled file processing operations
Stream Input/Output Classes and Objects

• ios:
– istream and ostream inherit from ios
• iostream inherits from istream and ostream.
• << (left-shift operator)
– Overloaded as stream insertion operator
• >> (right-shift operator)
– Overloaded as stream extraction operator
– Both operators used with cin, cout, cerr, clog, and
with user-defined stream objects
Stream-Insertion Operator
• << is overloaded to output built-in types
– Can also be used to output user-defined types
– cout << ‘\n’;
• Prints newline character
– cout << endl;
• endl is a stream manipulator that issues a newline character
and flushes the output buffer
Cascading Stream-Insertion/Extraction
Operators
• << : Associates from left to right, and returns a
reference to its left-operand object (i.e. cout).
– This enables cascading
– cout << "How" << " are" << " you?";

– cout << "1 + 2 = " << (1 + 2);



Stream Input
• >> (stream-extraction)
– Used to perform stream input
– Normally ignores whitespaces (spaces, tabs,
newlines)
– Returns zero (false) when EOF is encountered,
otherwise returns reference to the object from which
it was invoked (i.e. cin)
• This enables cascaded input
• cin >> x >> y;
Input /Output Streams
Features Of Iostream.h
The standard header file input and
output stream (iostream.h) contains a set
of small and specific general purpose
functions for handling input and output
data. The I/O stream is a sequence of
following characters written for the
screen display or read from the keyboard.
The standard input and output
operations in C++ are normally
performed by using the I/O stream as cin
for input and cout for output.
Various stream related header
files
C++ compilers Header Files To
Be Included
Borland C++ iostream . h, ios .h,
Turbo C++ iomanip . h
Microsoft Visual C++ iostream . h, ios .h,
Zortech C++ iomanip . h
ios . h, istream . h,
UNIX C++ (AT&T) ostream . h and
streamb . h
stream . h
stream . h
Various stream related header
files
• Ios.h
• Istream
• Ostream
• IOstream
istream.h
The istream consists of input functions
to read a streams of characters from the
keyboard.
ostream.h
The ostream consists of output
functions to write a character onto the
screen.
iostream.h

The iostream supports both


input/output stream of functions to
read a stream of characters form the
keyboard and to display a stream of
objects onto the video screen.
iostream.h
C++ does not have built-in input and output functions for
handling input and output of data from the outside
world, but it supports different kind of stream related
header files for providing these facilities. The stream
library is a hierarchy of classes. The streambuf class is
the basis of all streams. It defines the basic
characteristics of buffers that hold characters for input
and output. The ios class is derived from streambuf. It
defines the basic formatting and error control
capabilities used in streambuf. The ios is a virtual base
class for the classes istream (input stream) and ostream
(output stream). The iostream (input/output stream)
class is derived from both istream and ostream.
Keyboard and Screen I/O

• (a) Cout The cout is used to display an


object onto the standard device,
normally the video screen. The insertion
operator (the double less the sign <<) is
used along with the cout stream. The
general syntax of the cout stream is,
• Cout << variable 1 << variable 2 <<.....<<
variable n;
• (b) Cin The cin is used to read a number,
a character or a string of characters from
a standard input device, normally the
keyboard. The extraction operator (the
double greater then sign >>) is use along
with the cin operator.
The general syntax of the cin is
cin >> variable 1 >> variable 2 >>
…variable n;
• (c) Cerr and clog In addition to the
function cout, C++ provides other
functions of the class ostream
called cerr and clog. They are used to
redirect error messages to other devices.
The output of cerr is unbuffered, while
the output of clog is buffered.
(a) Endl the endl is an output manipulator
to generate a carriage return or line feed
character. The endl may be used several
times in a C++ statement.
For example,
(1)
cout << “ a “ << endl << “b” << endl;
(2)
cout << “ a = “ << a << endl;
cout << “ b = “ << b << endl;
#
#
main( )
{
Cout<< “Enter name” <<endl;
Cout<<“My name is Raj”;
getch();
}
Polymorphism

• The word polymorphism is derived from


Greek word Poly which means many and
morphos which means forms.
• Polymorphism can be defined as the ability to
use the same name for two or more related but
technically different tasks.
• Eg-woman plays role of daughter, sister, wife,
mother etc.
Overloading in C++

• What is overloading
– Overloading means assigning multiple
meanings to a function name or operator
symbol
– It allows multiple definitions of a function
with the same name, but different signatures.
• C++ supports
– Function overloading
– Operator overloading
Why is Overloading Useful?
• Function overloading allows functions that
conceptually perform the same task on
objects of different types to be given the
same name.

• Operator overloading provides a convenient


notation for manipulating user-defined
objects with conventional operators.
Function Overloading
• Is the process of using the same name for two
or more functions
• Requires each redefinition of a function to use
a different function signature that is:
– different types of parameters,
– or sequence of parameters,
– or number of parameters
• Is used so that a programmer does not have to
remember multiple function names
Function Overloading

• Two or more functions


can have the same name
but different parameters
Example: float max(float a, float
int max(int a, int b) b)
{ {
– if (a>= b) – if (a>= b)
– return a; – return a;
– else – else
– return b; – return b;
} }
void sum(int,int);
void sum(double,double);
void sum(char,char);
void main()
{
int a=10,b=20 ;
double c=7.52,d=8.14;
char e=‘a’ , f=‘b’ ;
sum(a,b);
sum(c,d);
sum(e,f);
}
void sum(int x,int y)
{
cout<<“\n sum of integers are”<<x+y;
}
void sum(double x,double y)
{
cout<<“\n sum of two floating no are”<<x+y;
}
void sum(char x,char y)
{
cout<<“\n sum of characters are”<<x+y;
}
• Output:
Sum of integers 30
sum of two floating no are 15.66
sum of characters are 195
SCOPE RULES

• Local Variable
• Global variable
• Local Variables are defined inside the
function body or in a compound
statement. The scope of these variables
are inside the function where they are
defined.
Eg: int fact (int n)
{
int i, fact, j; // i, j are local variables.
-----
----
}
• Global variables are those variables whose
scope is available through out the program.
Static Data Members
A data member of a class can be qualified as static. A
static member variable has certain special
characteristics. These are:-
• It is initialized to zero when the first object of its class
is created. No other initialization is permitted.
• Only one copy of that member is created for the entire
class and is shared by all the objects of that class, no
matter how many objects are created.
• It is visible only within the class, but its lifetime is the
entire program.
Static Data Members
• The type and scope of each static
member variable must be defined outside
the class definition.
• They are also known as class variables
since they are associated with the class
itself rather than with any class object.
Static Member Functions

• The main usage of static function is when the


programmer wants to have a function which is
accessible even when the class is not instantiated.
• Static member functions have a class scope and they
do not have access to the 'this' pointer of the class.
Static Member Functions
• Static function is defined by using the keyword
static before the member function that is to be
declared as static function.
static return_data_type function_name()
{
statement 1;
statement 2;
…….
…….
}
Static Member Functions
• The functions declared static or static functions are
accessed using only the class name and the scope
resolution operator, unlike in normal member functions
where these are not used.
• A static member function can only access static
member data, of the class.
Static Member Functions
• A non-static member function can be declared as
virtual but care must be taken not to declare a
static member function as virtual.
• It is possible to declare a data member of a class as
static irrespective of it being a public or a private
type in class definition.
Eg to store information of an employee, our structure
declaration may look like as shown overleaf

struct employee_type
{
int code;
char name[20];
int dept_code;
float salary;
};
• No variable has been associated with this
structure
• No memory is set aside for this structure.
Structure variable Declaration
• Syntax:-
Struct structure_name obj_name1, obj_name2;
At this point, the memory is set aside for the structure
variable employee.
Eg:- the object of structure student can be declare as
follows:
Struct student
{
Char name;
Int rollno;
Int reg no;
};
Object/ variable declaration

• Void main()
{
student data; //object declaration
data.name; //calling of name field
data.rollno; //calling of rollno field
data.regno; //calling of reg no field
}
How the elements of the structure variables
are stored in memory
1197
1198
var 1 1199
1200
1201
var 2 1202
1203
1204
1205
var 3
1206
1207
1208
var 4
1209
1210
1211
Intializing Structures

struct student_type
{
int rollno;
char name[25];
int age;
float height;
};
struct student_type student={1000,”Surbhi
salaria”,18,5.6};
Entering Data into Structures
Void main()
{
struct employee_type
{
int code;
char name[25];
char dept[15];
float salary;
}; continue
struct employee_type employee;
cout<<“\n\nParticulars of emp as entered by user\n”;
cout<<“\nEnter employee code:\n”; cout<<“\nEmployees code:”<<employee.code;
cin>>employee.code; cout<<“\nEmployee’s name:”<<employee.name;
cout<<“\nEmployee’s dept:”<<employee.dept;
cout<<“\nEnter name:\n”; cout<<“\nEmployee’s sal:”<<employee.salary;
gets(employee.name);
cout<<“\nEnter employee’s dept:\n”;
gets(employee.dept);
cout<< “\nEnter employee’s salary:\n”;
cin>>employee.salary; }
Use of Assignment Statement for
Structures
• Value of one structure variable can be assigned to
another variable of the same type using simple
assignment statement.if student1 and student2
are structure variable of type student_type,then
student2=student1;
Assigns value of structure variable student1 to
student2
WAP to copy structure elements
from one object to another object
#include<iostream.h>
#include<conio.h>
#include<string.h>
main()
{
Struct disk
{
Char name[15];
Float type;
Int price;
};
struct disk d1={“sony”,1.44,20};
struct disk d2,d3;
strcpy(d2.name,d1.name);
d2.type=d1.type;
d2.price=d1.price;
d3=d2;
Cout<<d1.name<<d1.type<<d1.price;
Cout<<d2.name<<d2.type<<d2.price;
Cout<<d3.name<<d3.type<<d3.price;
getch();
}
Difference b/t array and structure

• Structure is collection of different type of


data whereas array is same type of data.
• Keyword struct is used in case of structure
whereas no keyword in case of array
• Strucure has definition and declaration but
array has declaration only.
• Example to explain both.
To find avg marks of 3 subjects of 5
students Array of Structure

Void main()
{
Struct student
{
int subject1;
int subject2;
int subject3;
};
int i,total=0;
float av;
struct student st[20];
for(i=0;i<=5;i++)
{
cout<<“enter the marks of 3subjects of “<<i+1
<<“student”,;
cin>>st[i].subject1;
cin>>st[i].subject2;
cin>>st[i].subject3;
total= st[i].subject1+ st[i].subject2+ st[i].subject3;
av=total/3;
Cout<<“avg of marks of “<<i+1<<“student is=“<<av;
}
getch();
}
Array within Structure

when a array declared and processed within


a structure, then it is called array within
structure
struct name
{
char fname[10];
char lname[10];
};
Nested Structure

Structure can be embedded within another


structure,i.e when a structure declared and
processed within another structure,then it is
called nesting of structure
Syntax
Struct tag1
{
member elements-1;
…………………………………..
member element-m;
};
struct tag2
{
struct tag1 v1;
};
Struct tag2 v2;
Example
Void main()
{
stuct name
{
char fname[10];
char lname[10];
};
Struct bdate
{
int day;
int month;
int year;
};
struct data
{
struct name n;
struct bdate b;
};
struct data d;
Cout<<“enter name”;
Cin>>d.n.fname>>d.n.lname;
Cout<<“enter birth date”;
Cin>>d.b.day>>d.b.month>>d.b.year;
Cout<<“name”<< d.n.fname<<d.n.lname;
cout<<“DOB”<<d.b.day<<d.b.month<<d.b.yea
r;
}
Structure and Function

• The relationship of structure with the


function can be viewed as:-

1. Passing Structures to a function..


Passing Structure to a Function

Similar to passing array of variable,structure can


be passed to a function as argument
Syntax:
Data-type func-name(struct-variable); /*actual
argument*/
Read and display student grade by
using structure with function
struct student display(struct student m)
{
{ cout<<“\nRollno is “<<m.rn;
cout<< “\n Name is”<<m.name;
int rn; cout<< “\n Grade is:”<<m.grade;

char name[20]; }

char grade;
}s;
main()
{
cout<<“\nEnter rollno,name and grade of student:\n”;
cin>>s.rn>>s.name>>s.grade;
display(s);
getch();
}
UNION

• A union is variable that declares a set of


multiple variable (called members or
elements having different data-type)sharing
the same memory area
• The union require the bytes that are equal to
the number of bytes required for the largest
member.
It is declared in two ways:-
Union union-tag
{
Data-type-1 member-element-1;
--------------------------------------
Data-type-n meber-element-2;
}v1,v2,....vn;
Union union-tag
{
Data-type-1 member-element-1;
--------------------------------------
Data-type-n meber-element-2;
};
Union tag-name v1,v2,....vn;
Union item
{
int m;
float x;
char c;
} code;
This declare a variable code of type union
item.
Union
Union:
Union is similar as structure. The major distinction
between them in terms of storage.

In structure each member has its own storage location


whereas all the members of union uses the same location.

The union may contain many members of different data


type it can handle only one member at a time union can be
declared using the keyword union.
Example
void main()
{
enum days{sun,mon,tues,wed,thur,fri,sat};
days day1,day2;
day1=sun;
day2=fri;
cout<<day1<<“\t”<<day2;
if(day1>day2)
{
cout<<“day1 comes after day2”;
}
else
{
cout<<“day1 comes before day2”;
}
}
Class

• A class is a user define data type which holds


both data and function.
• The data included in the class i.e the internal
data is called the internal data or data
member and the functions included is called
the member function.
• These member functions can manipulate the
internal data of the class
Object

• Is an instant of a class.
• In terms of variables, class would be the type
and an object would be a variable.
Classes in C++

• A class definition begins with the keyword


class.
• The body of the class is contained within a set
of braces, { } ; (notice the semi-colon).

Any valid identifier

class class_name
{
…. Class body (data member +
…. methods)
….
};
Class name

• Name given to a particular class (any user


define name). It can also be called as tag
name of the class that act as the type
specifier for class using which we can create
objects.
• The class is specified by keyword “class”
Data Members

• Data type properties that describe the


characteristics of a class.
• We can declare any number of data members
of any type in a class.
• E.g. int x;
Member functions

• Various operations that can be performed to


data members of that class.
• We can declare any number of member
functions of any type in a class.
• E.g. void read();
Access Specifiers

• Used to specify access rights for the data


members and member functions of the class.
• Depending upon the access level of a class
member, access to it is allowed or denied.
• Within the body, the keywords private: and public:
specify the access level of the members of the
class.
– the default is private.
• Usually, the data members of a class are declared
in the private: section of the class and the
member functions are in public: section.
Classes in C++

private members or methods

class class_name
{
private: Public members or methods



public:



};
Private:
only members of that class have accessibility
• can be accessed only through member
functions of that class i.e by the functions
declared inside the class only.

• Private members and methods are for


internal use only.
Public:
• Accessible from both inside and outside the class also
i.e by the functions declared in the main() program
also.
Protected:
• Stage between private and public access.
• They can be accessed by the member function or friend
functions of the class. They are similar to private
members in the sense that they cannot be accessed by
the non- member functions of the class.
Class Example

• This class example shows how we can


encapsulate (gather) a circle information into
one package (unit or class)

No need for others classes to access


and retrieve its value directly. The
class methods are responsible for
that only.

class Circle They are accessible from outside


{ the class, and they can access the
private: member (radius)
double radius;
public:
void setRadius(double r); double
getDiameter();
double getArea();
double getCircumference();
};
Methods definition

• The member function of the class can be defined in two


different ways:
1) Inside the class definition:- The member functions are
simple defined inside the class only i.e the body of the
function resides inside the range of class only.
2) Outside the class definition: by using scope resolution
operator, which specifies that the scope of the function
is restricted to the class class_name.
Syntax:- class_name:: function_name
Inside the class definition
Eg: class abc
{
Private: Cout<<“rollno=“;
Int rollno; Cin>>rollno;
Char name[20]; }
Public: Void display()
Void getdata() {
{ Cout<<“name=“<<name;
Cout<<“name=“; Cout<<“rollno=“<<rollno;
Cin>>name; }
};
Outside the class definition
Eg: class abc Cin>>name;
{ Cout<<“rollno=“;
Private: Cin>>rollno;
Int rollno; }
Char name[20]; Void abc :: display()
Public: {
Void getdata(); Cout<<“name and rollno=“;
Void display(); Cout<<name<<rollno;
}; }
Void abc :: getdata()
{
Cout<<“name=“;
Declaring objects:
• A class declaration only uses to build the structure
of an object.
• Declaration of an object is same as declaration of
class.
• Defining objects of class data type is known as
class instantiation(instances of class)
• When we create objects during that moment ,
memory is allocated to them.
– Ex- class Circle c;
Introduction

• Arrays
– Structures of related data items
– Static entity - same size throughout program
• A few types
– C-like, pointer-based arrays
– C++, arrays as objects
Arrays
• Array
– Consecutive group of memory locations
– Same name and type
• To refer to an element, specify
– Array name and position number
• Format: arrayname[ position number ]
– First element at position 0
– n element array c:
– c[ 0 ], c[ 1 ]…c[ n - 1 ]
• Array elements are like normal variables
– c[ 0 ] = 3;
– cout << c[ 0 ];
• Performing operations in subscript. If x = 3,
– c[ 5 – 2 ] == c[ 3 ] == c[ x ]
Arrays
Name of array (Note that
all elements of this
array have the same
name, c)

c[0] -45

c[1] 6

c[2] 0

c[3] 72

c[4] 1543

c[5] -89

c[6] 0

c[7] 62

c[8] -3

c[9] 1

c[10] 6453

c[11] 78

Position number of the


element within array c
Declaring Arrays
• Declaring arrays - specify:
– Name
– Type of array
– Number of elements
– Examples
– int c[ 10 ];
» float hi[ 3284 ];
• Declaring multiple arrays of same type
– Similar format as other variables
– Example
» int b[ 100 ], x[ 27 ];
Examples Using Arrays
• Initializers
– int n[ 5 ] = { 1, 2, 3, 4, 5 };
– If not enough initializers, rightmost elements
become 0
– If too many initializers, a syntax error is generated
– int n[ 5 ] = { 0 }
– Sets all the elements to 0
• If size omitted, the initializers determine it
– int n[] = { 1, 2, 3, 4, 5 };
– 5 initializers, therefore n is a 5 element array
Examples Using Arrays
• Strings
– Arrays of characters
– All strings end with null ('\0')
– Examples:
– char string1[] = "hello";
– char string1[] = { 'h', 'e', 'l', 'l', 'o',
'\0’ };
– Subscripting is the same as for a normal array
– String1[ 0 ] is 'h'
– string1[ 2 ] is 'l'
• Input from keyboard
– char string2[ 10 ];
– cin >> string2;
– Takes user input
– Side effect: if too much text entered, data written
beyond array
Passing Arrays to Functions
• Specify the name without any brackets
– To pass array myArray declared as
» int myArray[ 24 ];
– to function myFunction, a function call would
resemble
» myFunction( myArray, 24 );
– Array size is usually passed to function
• Arrays passed call-by-reference
– Value of name of array is address of the first
element
– Function knows where the array is stored
• Modifies original memory locations
• Individual array elements passed by
call-by-value
– pass subscripted name (i.e., myArray[ 3 ]) to
function
Passing Arrays to Functions

• Function prototype:
– void modifyArray( int b[], int arraySize
);
– Parameter names optional in prototype
• int b[] could be simply int []
• int arraysize could be simply int
Sorting Arrays
• Sorting data
– Important computing application
– Virtually every organization must sort some data
• Massive amounts must be sorted
• Bubble sort (sinking sort)
– Several passes through the array
– Successive pairs of elements are compared
• If increasing order (or identical), no change
• If decreasing order, elements exchanged
– Repeat these steps for every element
Sorting Arrays

• Example:
– Original: 3 4 2 6 7
– Pass 1: 3 2 4 6 7
– Pass 2: 2 3 4 6 7
– Small elements "bubble" to the top
Computing Mean, Median and
Mode Using Arrays
• Mean
– Average
• Median
– Number in middle of sorted list
– 1, 2, 3, 4, 5 (3 is median)
• Mode
– Number that occurs most often
– 1, 1, 1, 2, 3, 3, 4, 5 (1 is mode)
Searching Arrays: Linear Search and
Binary Search
• Search array for a key value
• Linear search
– Compare each element of array with key value
– Useful for small and unsorted arrays
• Binary search
– Can only be used on sorted arrays
– Compares middle element with key
• If equal, match found
• If key < middle, repeat search through the first half of the
array
• If key > middle, repeat search through the last half of the
array
– Very fast; at most n steps, where 2^n > # of
elements
• 30 element array takes at most 5 steps
n
– 2 > 30

5
Multiple-Subscripted Arrays
• Multiple subscripts - tables with rows, columns
– Like matrices: specify row, then column.

Column 0 Column 1 Column 2 Column 3


• Initialize
Row 0 a[ 0 ][ 0 a[ 0 ][ 1 a[ 0 ][ 2 a[ 0 ][ 3
] ] ] ]
a[ 1 ][ 0 a[ 1 ][ 1 a[ 1 ][ 2 a[ 1 ][ 3
intRowb[
1 2 ][ 2 ] = { {1, 2}, {3, 4}};
] ] ] ]
Row 2 a[ 2 ][ 0 a[ 2 ][ 1 a[ 2 ][ 2 a[ 2 ][ 3
] ] ] ]
– Initializers grouped by row inColumn
bracessubscript
– int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
Array name
Row subscript

1 2
3 4

1 0
3 4
Multiple-Subscripted
Arrays

• Referenced like normal


– cout << b[ 0 ][ 1 ];
– Will output the value of 0
– Cannot reference with commas
– cout << b( 0, 1 );
• Will try to call function b, causing a syntax error
Pointers

These are the variables that are used


to hold the address of another
variable
Pointer variable
• A pointer is a variable that contains the memory
location of another variable.
• Syntax:-
• type * variable name
• You start by specifying the type of data stored in
the location identified by the pointer.
• The asterisk tells the compiler that you are
creating a pointer variable.
• Finally you give the name of the variable.
Declaration and Initialization

• Syntax for declaring pointer is


data_type * ptr variable name;
Example : int *p;

Syntax for Initialization of a pointer is


ptr var name= & var name;
Example : p=&a;
Declaring a Pointer Variable

• To declare ptr as an integer pointer:


– int *ptr;
• To declare ptr as a character pointer:
– char *ptr;
Address operator:
• Once we declare a pointer variable we must
point it to something we can do this by
assigning to the pointer the address of the
variable you want to point as in the following
example:
ptr=&num;
• This places the address where num is stores
into the variable ptr. If num is stored in
memory 21260 address then the variable ptr
has the value 21260.
Program to display variable value and
address value
Void main ()
{
int *p,a;
Clrscr();
Cout<<“enter the value of a”;
Cin>>a;
p=&a;
Cout<<“address of variable a using pointer is”<<p;
Cout<< value of variable a using pointer is”<<*p;
getch();
}

// variable address= p
// variable value=*p
Another Program

int a=20;
int *p;
p=&a;
Cout<<a<<&a;
Cout<<p<<&p<<*p;
P has an address 500
Variables, Addresses and Pointers

• main()
• Memory Value
{ • a (1001) 5
int a = 5; • b (1003) 6
int b = 6; • c (1005) 1001
int *c;
// c points to a
c = &a;
}
Pointer to pointer

Pointer variable that holds the address of


another pointer
Declaration :
int **p1,*p;
Initialization
p1=&p;
Pointers to pointers
• A pointer variable containing address of
another pointer variable is called pointer
to pointer
void main()
{
int a=2, *p, **q;
p=&a;
q=&p;
cout<<a<<“is stored at ”<<p<<“and pointer
is stored at ”<<q;}
Pointer Arithmetic
Void main()
{
Int *p,a,**p1;
Clrscr();
Cout<<“Enter the value of a”;
Cin>>a;
p=&a;
p1=&p;
Cout<<“address of variable a using ptr”<<p;
p=p+4;
Cout<<“modified address is”<<p;
Cout<<“value of variable a using ptr is”<<*p;
*p=*p+20;
Cout<<“modified value of variable a is ”<<*p;
Cout<<“address of pointer p is”<<p1;
getch();}
Pointer Arithmetic

void main()
{
int a=25,b=78,sum;
int *x,*y;
x=&a;
y=&b;
sum= *x + *y;
cout<<“Sum is : ”<<sum;
}
Assignment in pointers

• Pointer variables can be "assigned": int *p1,


*p2; p2 = p1;
– Assigns one pointer to another
– "Make p2 point to where p1 points"
• Do not confuse with: *p1 = *p2;
– Assigns "value pointed to" by p1, to "value pointed
to" by p2
Diagrammatic representation
Comparison in pointers
• Two pointers of the same type, p and q, may be
compared as long
• as both of them point to objects within a single
memory block
• • Pointers may be compared using the <, >, <=,
>=, == , !=
• • When you are comparing two pointers, you are
comparing the
• values of those pointers rather than the contents
of memory locations pointed to by these
pointers
Void Pointer

• It is called the Generic pointer


• It is a special type of pointer that can be
pointed at objects of any data type
• A void pointer is declared like a normal
pointer, using the void keyword as the
pointer’s type
• Example: void *pVoid; // pVoid is a void
pointer
Void Pointer (Contd)
A void pointer can point to objects of any data type
Example:
main()
{ int i;
char c;
void *data;
i = 6;
c = 'a';
data = &i;
cout<<"the_data points to the integer value "<< *(int *)data;
data = &c;
cout<<"the_data now points to the character "<< *(char*) data;
getch();
}
Other Properties of Void Pointer

• It Can’t be Dereferenced because void pointer


does not know what type of object it is
pointing to.
• It is not possible to do pointer arithmetic on a
void pointer.
• Since void pointers can’t be dereferenced,
there is no such thing as a void reference
Reference Variables
Reference variable = alias for another variable
- Contains the address of a variable (like a pointer)
- No need to perform any dereferencing (unlike a pointer)
- Must be initialized when it is declared

int x = 5;
int &z = x; // z is another name for x
int &y ; //Error: reference must be initialized
cout << x << endl; -> prints 5
cout << z << endl; -> prints 5

z = 9; // same as x = 9;

cout << x << endl; -> prints 9


cout << z << endl; -> prints 9
Reference Variables

int a=5;
int *p;
p=&a;
Cout<<p<<*p<<&p;
Int &b=a;
a=a+2;
Cout<<b;
Problems Associated With
Pointers: Null Pointer
• A null pointer is generally used to signify that
a pointer does not point to any object
• NULL pointer is a type of pointer of any data
type and generally takes a value as zero. This
is, however, not mandatory. This denotes that
NULL pointer does not point to any valid
memory address.
Example of Null Pointer

• int* exforsys;
• exforsys=0;
• The above statement denotes exforsys as an
integer pointer type that does not point to a
valid memory address. This shows that exforsys
has a NULL pointer value.
Difference between Null Pointer and
Void Pointer

A Void pointer is a special type of pointer of void


and denotes that it can point to any data type.
NULL pointers can take any pointer type, It
means pointer can’t point to anything .It
resolves the problem of dangling and wild
pointers.
Dangling Pointers

• Points to Invalid Location


• Dangling pointers arise when an object is
deleted or de allocated, without modifying
the value of the pointer, so that the pointer
still points to the memory location of the de
allocated memory.
Difference between dangling Pointer
and Null Pointer

• NULL pointer points to nothing. But dangling


pointers are those pointers which points to
invalid location (e.g. still points to those
memory locations which are already freed)
int *p = NULL;
Is mere a pointer which is not initialised to valid
memory location. it points to nothing int *q ;
q -> 0x1Ax
Strings in C++ The
string Class
• Definition of Strings
• How to declare strings in C++: the string class
• Operations on strings
– Concatenation, comparison operators, and [ ]
• Functions of the string class
– length, size, empty,
– insert, substr, replace, erase, clear, find
• Useful char functions in the C library
<ctype.h>
Definition of Strings

• Generally speaking, a string is a


sequence of characters
• Examples: “hello”, “high school”,
“H2O”.
• Typical desirable operations on strings
are:
– Concatenation:
“high”+“school”=“highschool”
– Comparisons: “high”<“school” //
alphabetical
– Finding/retrieving/modifying/deleting/inserti
ng substrings in a given string
Strings in C
• In C, a string can be a specially terminated char array
or char pointer
– a char array, such as char str[ ]=“high”;
– a char pointer, such as char *p = “high”;
• If a char array, the last element of the array must be
equal to ‘\0’, signaling the end
• For example, the above str[] is really of length 5:
str[0]=‘h’ str[1]=‘i’ str[2]=‘g’ str[3]=‘h’ str[4]=‘\0’
• The same array could’ve been declared as:
– char str[5] = {‘h’,’i’, ‘g’,’h’,’\0’};
• If you write char str[4] = {‘h’,’i’, ‘g’,’h’};, then str is
an array of chars but not a string.
• In char *p=“high”; the system allocates memory of 5
characters long, stores “high” in the first 4, and ‘\0’ in
the 5th.
The string Class in C++

• C++ has a <string> library


• Include it in your programs when you
wish to use strings: #include <string>
• In this library, a class string is defined
and implemented
• It is very convenient and makes string
processing easier than in C
Declaration of strings

• The following instructions are all equivalent.


They declare x to be an object of type string,
and assign the string “high school” to it:
– string x(“high school”);
– string x= “high school”;
– string x; x=“high school”;
Comparison Operators for
string Objects
• We can compare two strings x and y using the
following operators: ==, !=, <, <=, >, >=
• The comparison is alphabetical
• The outcome of each comparison is: true or
false
• The comparison works as long as at least x or
y is a string object. The other string can be a
string object, a C-style string variable, or a
double-quoted string.
What if You Want to Use
C-Style Strings
• You can!
• C has a library <strings.h> which provides
several string processing functions
• Some of the more commonly used functions
in that library are presented in the next two
slides
• In those functions, most of the arguments are
of type char *str. That can be replaced by
char str[];
C Library <strings.h> for
String Operations

• char *strcpy(char *dst, char *src);


– Copies the string src to string dest
• char *strncpy(char *dst, char *src,
int n);
– Copies the first n characters of src to dest
• char * strcat(*dst, char *src);
– Concatenate src to the end of dst.
• char * strcat(*dst, char *src, int n);
– Concatenate first n chars of src to end of dst.
• int strcmp(char *str1, char *str2);
– Returns 0 if str1=str2, negative if str1<str2, positive if str1>str2
• int strncmp(char *str1, char *str2, int n);
– Same as strcmp except it considers the first n chars of each string
• int strlen(char *str); // returns the length of str
• char * strchr(char *str, int c);
st
– Returns a char pointer to the 1 occurrence of character c in
str, or NULL otherwise.
• char * strstr(char *str, charst *pat);
– Returns a char pointer to the 1 occurrence of string pat in
str, or NULL otherwise.
• Plus some other commands
• Remarks:
– in strcpy, strncpy, strcat, and strncat, make sure that the dst string has
enough space to accommodate the string copied or cancatenated to it
– If the strings are arrays, also make sure that the array dst is large
enough to to accommodate the string copied or cancatenated to it
Correspondence between the C
library and the C++ string
Class
C Library Functions C++ string
operators/methods
strcpy = (the assignment operator)
strcat += (assign+concat operator)
strcmp = =, !=, <, >, <=, >=
strchr, strstr .find( ) method
strrchr .rfind( ) method
strlen .size( ) or .length( )
methods
Char Functions in C (and
C++)
• The <ctype.h> library in C provides
useful functions for single char
variables
• The next slide gives the most common
char functions.
• Although the input argument appears
to be of type int, it is actually a char.
Constructors

A special member function having


same name as that of its class which
is used to initialize some valid
values to the member variables.
Key points while defining constructor
• A constructor has same name as that of the
class to which it belongs.
• A constructor is executed automatically
whenever the object is created
• A constructor doesn`t have a return type, not
even void
• We can declare more than one constructor in a
class. These constructor differ in there
parameter list.
• If you don’t provide a constructor of your own
then the compiler generates a default
constructor (expects no parameters and
has an empty body).
Contd..

• Constructor should be declared in the public


section of the class. If it is not declared in
public section of the class then the whole
class become private . By doing this the
object of the class created from outside
cannot invoke the constructor which is the
first member function to be executed
automatically.
Syntax

class CLASSNAME
{
public:
CLASSNAME([parameter list]);
};
Example
#include<iostream.h>
#include<conio.h>
class Rectangle
{
private:
int length,breadth;
public:
Rectangle()
{
Length=5,breadth=6;
}
void area()
{
int a=(length*breadth);
cout<<“area is”<<a;
}
};
void main()
{
clrscr();
Rectangle r1;
r1.area();
getch();
}
Parameterized Constructor

In order to initialize various data elements


of different objects with different values
when they are created. C++ permits us to
achieve this objects by passing argument to
the constructor function when the object are
created . The constructor that can take
arguments are called parameterized
constructors
class abc { int m, n; public: abc (int x, int y);
// parameterized constructor ................
................. }; abc : : abc (int x, int y) { m = x;
n = y; }
Parameterized constructor

#include<iostream.h>
class Rectangle
{
private:
int length,breadth;
public:
Rectangle(int a,int b)
{
length=a,breadth=b;
}
void area()
{
int a=(length*breadth);
cout<<“area is”<<a;
}
};
void main()
{
clrscr();
Rectangle r1(5,6);
Rectangle r2(7,8);
r1.area();
getch();
}
Copy constructor

• A constructor is a constructor that creates a


new object using an existing object of the
same class and initializes each data member
of newly created object with corresponding
data member of existing object passed as
argument.since it creates a copy of an existing
object so it is called copy constructor.
Example

Class counter
{
Int c;
public:
Counter();
Counter(int a)
{
C=a;
}
Counter(counter &ob)
{
cout<<“copy constructor invoked”;
C=ob.C;
}
}
Void show()
{
cout<<C;
};
Void main()
{
Clrscr();
Counter C1(10);
Counter C2(C1);
C1.show();
C2.show();
getch();
}
Default Constructor

• A constructor with no parameter is called a


default constructor. It is used for initializing
the object of a class. In other words, a default
constructor initializes the data member with
no arguments.
• Eg:- abc obj(5); // passing parameter
abc obj; //no parameter
passing
EXAMPLE
• Class data Cout<<“entered data is”;
{ Cout<<a<<b<<c;
Private: }
Int a, float b, char c[20]; Void main()
Public: {
data(); //default constructor Data obj;
Void putdata(); Obj.putdata();
}; getch();
Data::data() }
{ a=0;
b=0; c=‘\0’ }
Void data :: putdata()
{
Destructors

Is a member function having same


name as that of constructor but it is
preceded by a tilde(~) symbol and is
executed automatically when object
of a class is destroyed
Need for Destructors
• To de-initialize the objects when they are
destroyed
• To clear memory space occupied by a data
member.
syntax

class CLASSNAME
{
……………….
public:
~CLASSNAME();
};
Example
main()
{ void xyz()

Class abc {

{ If(a>b)

Private: big=a;

Int a, b, big; Else

Public: big=b;

abc() Cout<<“big no is”<<big;

{ }

Cout<<“enter two numbers”; ~abc()

Cin>>a>>b; } {
cout<<destructor is under wrk”;}
};
Class abc obj;
obj.xyz();
}
Pointers and classes

• Pointers are variables which hold the memory


address of other variable. The use of pointers
in classes is similar to that of pointer used
with structure.
• By using pointers any member function can
be accessed by two methods:
(*ptr).function_name;
Or
Ptr->function_name;
What is a constructor?
• It is a special type of member function
whose task is to initialize the objects of
the class.
• A constructor has:
(i) the same name as the class itself
(ii) no return type
class marks
{
int n, m;
public:
marks()
{
n=12;m=13;
}
void add()
{
cout<<(n+m);
}
};
void main()
{
marks ob;
ob.add();
}
Comments on constructors
• A constructor is called automatically whenever a
new instance of a class is created.
• You must supply the arguments to the
constructor when a new instance is created.
• If you do not specify a constructor, the compiler
generates a default constructor for you (expects
no parameters and has an empty body).
Special characteristics of constructors

• They should be declared in the public section.


• They are invoked automatically when the objects
are created.
• They should not have return types, not even void
and therefore can’t return values.
• They can’t be inherited through a derived class.
• They can have default arguments.
Comments on constructors
(cont.)
• void main()
• {
• rectangle rc(3.0, 2.0);

• rc.posn(100, 100);
• rc.draw();
• rc.move(50, 50);
• rc.draw();
• }

• Warning: attempting to initialize a data member


of a class explicitly in the class definition is a
syntax error.
Parameterized Constructor

In order to initialize various data


elements of different objects with
different values when they are created.
C++ permits us to achieve this objects by
passing argument to the constructor
function when the object are created .
The constructor that can take arguments
are called parameterized constructors
class abc { int m, n; public: abc (int x, int y);
// parameterized constructor ................
................. }; abc : : abc (int x, int y) { m = x;
n = y; }
class book
{
int price;
int year;
public:
book(int x, int y);
void putdata();
book();
};
book::book(int x, int y)
{
price=x;
year=y;

}
void book::putdata()
{

cout<<"price is"<<price<<"\n";
cout<<"year is"<<year<<"\n";
}
book::book()
{
price=0;
year=0;

}
int main()
{
book b1,b2(10,50);
b1.putdata();
b2.putdata();
getch();
}
Multiple Constructors
in a class
class marks
{
int n, m;
public:
marks()
{
n=0; m=0;
}
marks(int x,int y)
{
n=x; m=y;
}
void add()
{
cout<<(n+m);
}
};
void main()
{
marks ob(4,5);
ob.add();
}
Copy Constructor
A copy constructor is a special in
constructor

the used to create a new


C++ programming language object as a copy

of an existing object. The first argument


of such a constructor is a reference to an
object of the same type as is being
constructed (const or non-const), which
might be followed by parameters of any
type (all having default values).
Copy Constructor
Copying of objects is achieved by the
use of a copy constructor and an .
assignment operator

A copy constructor has as its first


parameter a (possibly const or volatile)
reference to its own class type. It can
have more arguments, but the rest must
have default values associated with
them.
Copy constructor
• It is a member function which initializes
an object using another object of the
same class.
• A copy constructor has the following
general function prototype:
class_name (const class_name&);
#include<iostream.h>
Class code
{
int id;
Public:
code() { }
code(int a) { id = a; }
code (code & x)
{ id = x. id; }
void display()
{ cout<<id; }
};
Int main()
{
code A(100);
code B(A);
code C = A;
code D;
D = A;
A.display();
B.display();
C.display();
D.display();
return 0; }
Defining copy constructors is
very important

• In the absence of a copy constructor,


the C++ compiler builds a default copy
constructor for each class which is
doing a memberwise copy between
objects.
• Default copy constructors work fine
unless the class contains pointer data
members ... why???
void string::copy(char *c)
{
strcpy(s, c);
}

void main()
{
string str1("George");
string str2 = str1; // default copy constructor

str1.print(); // what is printed ?


str2.print();

str2.copy("Mary");

str1.print(); // what is printed now ?


str2.print();
}
Defining a copy constructor for the
above example:

class string {
private:
char *s;
int size;
public:
string(char *); // constructor
~string(); // destructor
string(const string&); // copy constructor
void print();
void copy(char *);
};
string::string(const string& old_str)
{
size = old_str.size;
s = new char[size+1];
strcpy(s,old_str.s);
}

void main()
{
string str1("George");
string str2 = str1;
str1.print(); // what is printed ?
str2.print();
str2.copy("Mary");
str1.print(); // what is printed now ?
str2.print();
}

Note: same results can be obtained by overloading the


assignment operator.
Following cases may result in
a call to a copy constructor

• When an object is returned by value


• When an object is passed (to a
function) by value as an argument
• When an object is thrown
• When an object is caught
• When an object is placed in a
brace-enclosed initializer list
Dynamic Constructor
The constructors can also be used to
allocate memory while creating objects.
This will enable the system to allocate
the right amount of memory for each
object when the objects are not of the
same size, thus resulting in the saving of
memory. Allocation of memory to
objects at the time of their construction
is known as dynamic construction of
objects. The memory is allocated with
the help of
new operator
# include <iostream.h>
# include <conio.h>
# include <string.h>
class str
{
char *name;
int len;
public:
str()
{
len=0;
name=newchar[len+1];
}
str(char *s)
{
len=strlen(s);
name=newchar[len+1];
strcpy(name,s);
}
void show()
{ cout<<"NAME IS:->"<<name<<endl;
}
void join(str &a,str &b);
};
void str::join(str &a,str &b)
{
len=a.len+b.len;
delete new;
name=newchar[len+1];
strcpy(name,a.name);
strcat(name,b.name);
};
void main()
{
clrscr();
char *first="HARSHIL";
str n1(first), n2("NINAD"), n3("PRATIK"), n4,
n5;
n4.join(n1,n2);
n5.join(n4,n3);
n1.show();
n2.show();
n3.show();
n4.show();
n5.show();
}
Composition: objects as members
of classes

• A class may have objects of other classes as


members.

• class properties {
• private:
• int color;
• int line;
• public:
• properties(int, int); // constructor
• };

• properties::properties(int c, int l)
• {
• color = c;
• line = l;
• }
Composition: objects as members
of classes (cont.)
class rectangle {
private:
float height;
float width;
int xpos;
int ypos;
properties pr; // another object
public:
rectangle(float, float, int, int ); // constructor
void draw(); // draw member function
void posn(int, int); // position member function
void move(int, int); // move member function
};
Composition: objects as members
of classes (cont.)
rectangle::rectangle(float h, float w, int c, int l):pr(c, l)
{
height = h;
width = w;
xpos = 0;
ypos = 0;
};

void main()
{
rectangle rc(3.0, 2.0, 1, 3);

C++ statements;
}
What is a destructor?
• It is a member function which deletes an
object.
• A destructor function is called automatically
when the object goes out of scope:
– (1) the function ends
– (2) the program ends
– (3) a block containing temporary variables ends
– (4) a delete operator is called
• A destructor has:
– (i) the same name as the class but is preceded by a
tilde (~)
– (ii) no arguments and return no values
class string {
private:
char *s;
int size;
public:
string(char *); // constructor
~string(); // destructor
};

string::string(char *c)
{
size = strlen(c);
s = new char[size+1];
strcpy(s,c);
}

string::~string()
{
delete []s;
}
Comments on destructors
• If you do not specify a destructor, the
compiler generates a default destructor
for you.
• When a class contains a pointer to
memory you allocate, it is your
responsibility to release the memory
before the class instance is destroyed.
#include <iostream.h>
#include <string.h>

class string {
private:
char *s;
int size;
public:
string(char *); // constructor
~string(); // destructor
void print();
void copy(char *);
};

void string::print()
{
cout << s << endl;
}
Data File Handling
Introduction

• Computer programs are associated to


work with files as it helps in storing data
& information permanently.
• File - itself a bunch of bytes stored on
some storage devices.
• In C++ this is achieved through a
component header file called fstream.h
Why to use Files:

• Convenient way to deal large quantities of


data.
• Store data permanently (until file is deleted).
• Avoid typing data into program multiple
times.
• Share data between programs.
We need to know:
how to "connect" file to program
how to tell the program to read data
how to tell the program to write data
error checking and handling EOF
• A file can be opened in two ways:
1. Using constructor function
2. Using member function
Opening file using constructor

• File name is used to initialize the file stream


object.
• Steps:-
1. Create a file stream object to manage stream
with appropriate class.
2. Initialize the file object with desired name.
Contd……..

• ofstream outfile(“results”); //it opens a file


name “result” for output.

• ifstream infile(“data”);
outfile<<“total”;
outfile.close();
infile>> string;
Opening files using member
function open()
• This function is used to open multiple files
that uses same stream object.
• Syntax:-
file_stream class stream_object;
stream_object.open(“filename”);
Example
ofstream outfile;
outfile.open(“Data”);
…………………..
…………………..
outfile.close();
outfile.open(“Data2”);
…………………….
…………………..
outfile.close();
Open(): File Modes

• We can have two arguments in open(), to


specify the file-mode.

stream-object.open(“filename”,mode);

the second argument specifies the purpose for


which file is opened.
Stream state member
functions
• In C++, file stream classes inherit a stream state
member from the ios class, which gives out the
information regarding the status of the stream.
For e.g.:
– eof() –used to check the end of file
character
– fail()- used to check the status of file at
opening for I/O
– bad()- used to check whether invalid file
operations or unrecoverable error .
– good()- used to check whether the
previous file operation has been
successful
EXAMPLES

• EOF()
Void main()
{
Ifstream infile;
Infile.open(“text”);
While(!infile.eof())
{
------
-----
}}
• FAIL()
Main()
{
Ifstream infile;
Infile.open(“text”);
While(!infile.fail())
{
Cout<<“cudn’t open a file”;
}}
Reading and Writing in Files

• Reading and Writing a character from a file


can be done by
• Get()
• Put()
• Get():- This is used to read an alphanumeric
character from a specified file.
• Put():- This is used to write an alphanumeric
character to specified file.
Reading and writing by insertion
and extraction
Stream Insertion Operators
• Are defined in the ostream class
• The operator “<<” is called the inserter
Stream Extraction Operators
• Are defined in the istream class and are
used to receive data from the input device
• The operator “>>”, called the extractor.
By Read () and Write()

• Read and write is used when we are dealing


with classes.
• Syntax:-
Read((char*)&obj sizeof(obj));
Write((char*)&obj,sizeof(obj));
EXAMPLE
MEMBER FUNCTIONS

• ios::app = append at end of file


• Ios::ate = go to end of file on opening instead
of beginning.
• Ios::binary=binary file
• Ios::in = open file for reading only
• Ios::out = open file for writing only
• Ios:: trunc = delete the content of file if it
exists
• Ios::nocreate = open fails if file doesn’t exist.
EXAMPLE

1) ofstream fileout;
fileout.open(“hello”,ios::app);
2)fileout.open(“hello”, ios::in | ios::out);
Files
• A file is a collection of related data stored
in a particular area on the disk.
• Programs can be designed to perform
the read and write operations on these
files
• A program involves either or both of
following kinds of data communication:
– Data transfer between the console unit and the
program
– Data transfer between the program and a disk
file
Introduction
• Computer programs are associated to work
with files as it helps in storing data &
information permanently.
• File - itself a bunch of bytes stored on some
storage devices.
• In C++ this is achieved through a component
header file called fstream.h
• The I/O library manages two aspects- as
interface and for transfer of data.
• The library predefine a set of operations for
all file related handling through certain
classes.
• C++ provides a new technique for
handling I/O operations through
mechanism known as streams.
• A stream refers to a flow of data.
• Classified in 2 categories:
1. Output stream
2. Input stream
In output stream flow of data is from
program to the output device.
In input stream the flow of data is from
input device to a program in main
memory.
Classes for file stream
operations
• The I/O system of C++ contains a set of
classes that define the file handling
methods.
• These include:
– ifstream
– ofstream
– fstream
– These classes are derived from fstreambase
and from corresponding iostream class
Why to use Files:
• Convenient way to deal large quantities of data.
• Store data permanently (until file is deleted).
• Avoid typing data into program multiple times.
• Share data between programs.
• We need to know:
how to "connect" file to program
how to tell the program to read data
how to tell the program to write data
error checking and handling EOF
Opening and closing a file
• If we want to use a disk file, we need to
decide the following things:
– Suitable name for the file
– Data type and structure
– Purpose
– Opening Method
Filename
• The file name is a string of characters
that make up a valid filename for the
operating system.
• It has two parts, a primary name and an
optional period with extension
• Example:
– Input.data
– Test.doc
Opening a file
• For opening a file, we must first create a
file stream and then link it to the
filename.
• A file stream can be defined using the
classes ifstream, ofstream and fstream
that are contained in the header file
fstream
• A file can be opened in two ways:
– Using a constructor function of the class
– Using the member function open() of the class
Opening files using constructor
• Constructor is used to initialize an object
while it is being created. Here, a filename
is used to initialize the file stream object.
• This involves following steps:
– Create a file stream object to manage the
stream using appropriate class
– Initialize the file object with the desired
filename.
• For example:
– ofstream outfile(“results”); // output only
• This creates outfile as an ofstream object
that manages the output stream.
• This statement opens the file results and
attaches it to the output stream outfile
• The following statement declares infile
as an ifstream object and attaches it to
the file data for reading
– ifstream infile (“data”); //input only
– The program may contain statements like:
– outfile<<total;
– outfile<<sum;
– infile>>number;
– infile>>string
• We can also use same file for both reading
and writing data
Program1
……..
ofstream outfile(“salary”); //creates outfile and connects “salary”
to it
……...
Program2
……….
ifstream infile(“salary”); //creates infile and connects “salary” to
it
– ………
• Instead of using two program, one for
writing data and another for reading
data, we can use single program to do
both operations on file.
– …..
– outfile.close(); //disconnect salary file from
outfile
– ifstream infile(“salary”); // and connect to
infile
– …..
– …..
– infile.close();
example
#include<fstream.h> ifstream inf(“item”);
#include<iostream.h> inf>>name;
main()
{ char name[30]; inf>>cost;
float cost; cout<<”item
ofstream name”<<name;
outf(“item”); cout<<“item
cout<<“enter item cost”<<cost;
name”;
cin>>name; inf.close();
outf<<name; getch();
cout<<“enter cost”; }
cin>>cost;
outf<<cost<<“\n”;
outf.close();
Opening file using Open()
• This function is used to open multiple
files that uses same stream object.
• Syntax:-
file_stream class stream_object;
stream_object.open(“filename”);
ofstream outfile;
outfile.open(“Data1”);
…………………..
…………………..
outfile.close();
outfile.open(“Data2”);
…………………….
…………………..
outfile.close();
#include<fstream.h> const int n=80;
#include<iostream.h> char line[n];
main() ifstream fin;
{ ofstream fout; fin.open(“country”);
fout.open(“country”); cout<<“contents of country
fout<<“usa\n”; file”;
fout<<“uk\n”; while(fin)
fout<<“india\n”; { fin.getline(line,n);
fout.close(); – cout<<line;
}
fout.open(“capital”); fin.close();
fout<<“washinton\n”; fin.open(“capital”);
fout<<“london\n”; cout<<“contents of capital
fout<<“india\n”; file”;
fout.close(); while(fin)
{ fin.getline(line,n);
– cout<<line;
}
fin.close();
getch();
}
Detecting end-of-file
• This condition is necessary for preventing
any further attempt to read data from the
file.
while(fin)
here fin is ifstream object which returns a
value 0 if any error occur in file including
end-of-file condition.
if(fin1.eof()!=0)
{ exit(1);}
eof() is a member function of class ios. It
returns non zero value if the end-of-file(eof)
condition is encountered and zero
otherwise.
Reading from files simultaneously
fin1.getline(line,size);
#include<fstream.h> cout<<"capital of"<<line;
#include<iostream.h> if(fin2.eof()!=0)
#include<conio.h> {
#include<stdlib.h> cout<<"exit from capital\n";
main() exit(1);
{ }
const int size=80; fin2.getline(line,size);
char line[size]; cout<<line<<endl;
}
ifstream fin1, fin2; getch();
fin1.open("country"); }
fin2.open("capital");
for(int i=1;i<=3;i++)
{
if(fin1.eof()!=0)
{ cout<<"exit from
country\n";
exit(1);
}
Open(): File Modes
• We can have two arguments in open(), to specify
the file-mode.
stream-object.open(“filename”,mode);
the second argument mode specifies the purpose
for
which file is opened and mode known as file mode
parameter.
Parameter Meaning
ios::app Append to
end-of-file
ios::ate Go to end of file on
opening
ios::binary Binary file
ios::in Open file for
reading only
ios::nocreate Open fail if file
does not exist
ios::noreplace Open fail if file already
exist

ios::out Open file for


writing only
ios::trunc Delete contents of
file
• fstream fileout;
fileout.open(“hello”,ios::app);
• void main()
{
fstream infile;
Infile.open(“data_file”, ios::in|ios::out)
----
-----
}
File pointers and their
Manipulations
• Each file has two associated pointers
known as the file pointers.
• Input pointer/get pointer
• Output pointer/put pointer
Default actions
• In read only mode the Input pointer is
automatically set at the beginning.
• In write only mode, the existing contents are
deleted and output pointer is set at the
beginning.
• In append mode, the output pointer moves to
the end of file.
• File opened in read mode:
– I/p pointer automatically set at beginning.
• File opened in write mode:
– Existing contents deleted & O/p pointers sets at beginning.
• To add more data, file is opened in append mode.
Functions for manipulation of file
pointer
• To move the file pointer to any other desired
position inside the file. The file stream classes
support the following to manage such situations:
– seekg()- moves get pointer to specified location
– seekp()- moves put pointer to specified location
– tellg()- gives the current position of get pointer
– tellp()- gives the current position of put pointer
Example
ofstream file1;
file1.open(“result”, ios::app);
int p=file1.tellp();
The value of p will represent the number of
bytes in the file.
Infile.seekg(10);
Moves the file pointer to the byte number
10.
Sequential input and output
operations
• put(),get() used to handle single
character at a time.
• write(), read() functions are used to
handle a stream of data.
file.put(string);
file.get(ch);
main()
{
char string[80];
cout<<“enter a string”;
cin>>string;
int len= strlen(string);
fstream file;
file.open(“text”, ios::in|ios::out);
for(i=0;i<len;i++)
file.put(string[i]);
file.seekg(0);
char ch;
while(file)
{file.get(ch);
cout<<ch;
}}
write() and read()

• infile.read((char *)&V, sizeof(V));


• outfile.write((char *)&V, sizeof(V));
These functions take two arguments, first is
address of variable V, second is length of
that variable in bytes.
Example
main()
{
float height[4]={175.5,153.0};
ofstream outfile;
outfile.open(filename);
outfile.write(( char *)& height,sizeof(height));
outfile.close();
Reading and Writing Class
object
• The binary input output read() and
write() are designed to write and read
from disk file objects.
• These functions handles entire structure
of an object as a single unit .
• function write() copies a class object
from memory byte by byte with no
conversion.
Example
void main()
{
fstream file;
inventory iobj;
file.open(“STOCK”, ios:: in|ios::out);
cout<<“enter detail for items”;
iobj.readdata();
file.write((char*) & iobj,sizeof(iobj));
File.seekg(0);
file.read((char*) & iobj ,sizeof(iobj));
iobj.writedata();
file.close();
}
Updating a file
• Updating means to perform following
tasks:
1. Displaying the contents of file
2. Modifying the existing file
3. Adding a new item
4. Deleting an existing item.
• These actions require the file pointers to
move to a particular location.
• This can be easily implemented if file
contains objects of equal length.
• Size of each object can be obtained
using:
int ob_len= sizeof(object);
Then location of desired object is:-
int location=m*ob_len;
• total number of objects in a file:-

int n=file_size/ob_len;
Inheritance
• The mechanism of creating a new class
from an existing class is known as
inheritance.
Types of Inheritance
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance
• Syntax:
class DerivedClassName : access-level BaseClassName
where
– access-level specifies the type of derivation
• private by default
• Public
• Protected
• Any class can serve as a base class
– Thus a derived class can also be a base class
Examples
Class ABC : private XYZ//private derivation
{
Members of ABC
};
Class ABC : public XYZ //public derivation
{
Members of ABC
};
Class ABC : XYZ //private derivation by default
{
Members of ABC
};
Public vs private inheritance
• The public keyword in the inheritance
syntax means that publicly accessible
members inherited from the base class
stay publicly accessible in the derived
class
• But sometimes its preferable to inherit
the public members of a parent in such a
way that they become private in the child
Private inheritance
• Public members of base class become
private members of derived class
• Public and protected members are only
available to derived-class member
functions - not to a derived object.
Protected inheritance
• private members of the base class are
not accessible in the derived class (to
preserve encapsulation)
• Protected qualification allows
encapsulated data members which are
not publicly accessible to be accessible
by derived classes
• ("Protected" members are not accessible
from outside the class, except in derived
classes)
Class B

Not
Private Inheritable
Protecte
d
Public
ClassD2:private B
Class D1:public
B
Private Private
Protecte Protected
d Public
Public

Class X:public D1,protected


D2
Private
Protect
ed
Public
#include<iostream.h> class D:public B
//public
Class B derivation
{ {
Int a; //private not Int c;
inheritable
Public: //ready for Public:
inheritance Void mul(void);
Int b; Void display(void);
Void get_ab(); };
Int get_a();
Void show_a();
};
Void B:: get_ab(void) Void D::mul()
{ {
a=5;b=10; c= b*get_a();
} }
Int B::get_a() Void D::display()
{ {
Return a; Cout<<“a=“<<get_a()<
} <“\n”;
Void B::show_a() Cout<<“b=“<<b<<“\n”;
{ Cout<<“c=“<<c<<“\n”;
Cout<<“a=“a<<“\n”; }
}
#include<iostream.h>
Class B
{
Int a;
Public:
Int b
Void get_ab();
Int get_a();
Void show_a();
};
Int main() Output
{ a= 5
D d; a=5
d.get_ab(); // b = 10
d.mul(); c = 50
d.show_a(); // a= 5
d.display(); b = 20
c = 100
d.b=20; //
d.mul();
d.display();
Return 0;
}
Multilevel Inheritance
Class test : public student //first
#include <iostream.h> level
Class student { derivation
{ Protected:
Protected: – Float sub1,sub2;
int roll_no; Public:
Public: void get_marks(float,float);
void get_no(int); void put_marks(void);
void put_no(void); };
}; void test::get_marks(float x,float y)
Void student::get_no(int a) { Sub1=x; sub2=y;}
{ Roll_no=a;} Void test::put_marks()
Void student ::put_no() { cout<<“Marks in sub1”<<sub1;
cout<<“Marks in sub2”<<sub2;}
{ cout<<“Roll number
is”<<roll_no; Class result::public test //second
level derivation
}
{ float total ;
public:
void display(void) ;}
Void result:: display(void)
{
Total= sub1+sub2;
Put_no(); //function of class student
Put_marks(); //function of class test
Cout<<“Total = “<<total;
}
Int main()
{
Result student1;
Student1.get_no(102);
Student1.get_marks(80.0,98.5);
Student1.display();
Return 0;
}
Multiple Inheritance
#include <iostream.h> Class P:public M, public N
Class M {
{ Public:
Protected: void display(void);
int m; };
Public: Void M::get_m(int x)
void get_m(int); { m=x;}
}; Void N::get_n(int y)
Class N { n= y;}
{ Void P::display(void)
Protected: {
int n; Cout<<“m=“<<m<<“\n”;
Public: Cout<<“n=“<<n<<“\n”;
void get_n(int); Cout<<“m*n=”<<m*n<<“\n
}; ”;
}
Multiple Inheritance
Int main()
{
P p;
p.get_m(10); //m=10
p.get_n(20); //n=20
p.display(); //m*n = 200
Return 0;
}
Overriding Member Functions
A derived class function having same name and
parameters as a base class function will always
overrides the base class function.

Multiple Single
A B A

C B

C1.B::input()
Overriding in Single Inheritance
#include<iostream.h>
#include<conio.h> void show(int b)
class A { y=b;
{ int x; cout<<"y of class B =
public: "<<y<<"\n";
void show(int a) }
{ };
x=a; int main()
cout<<"x of class A = {
"<<x<<"\n"; B obj;
}
};
obj.show(10);
class B: public A
{
getch();
int y;
public:
return 0;
}
Ambiguity resolution in Inheritance
Class M Class P:public M, public N
{ {
Public: Public:
void display(void) void display(void)
{ {
cout<<“class M”; M::display();
} }
}; };
Class N // Ambiguity may also arise
{ in single inheritance .
public: Derived class overrides
the inherited function
void display(void)
{
cout<<“class N”;
}
};
Hybrid Inheritance
Record – Student
– Test score
Marks Avg –
– result
Result – //Multiple copies of
the variables of
student class are
generated
Virtual base class
Class A
{ …….
– A ………..};
– B1 B2 Class B1:virtual public

A
– C {…….
…….};
Class B2:public virtual
A
{…….
……..};
Class C:public
B1,public B2
{………
………}; //only one
copy of A will
be inherited
Virtual base class
class test : virtual public
student
class student
{
{ protected: float part1,part2;
protected: int roll_no; public:
public: void get_marks(float x,
float y)
void get_no(int a)
{ part1=x; part2=y;}
{ void put_marks()
roll_no=a; { cout<<“marks
} obtained”<<“part1”<<part1<
<“part2”<<part2;}
void put_no(void) };
{ class sports: public virtual
cout<<“roll no. student
:”<<roll_no; {
} protected : float score;
public:
};
void get_score(float s)
{ score=s; }
Virtual base class
void put_score() int main()
{ {
cout<<“sports wt:”<<score; result student1;
} student1.get_no(100);
}; student1.get_marks(50.5,65.
class result : public test , public 2);
sports student1.get_score(10.5);
{ student1.display();
float total; return 0;
public: }
void display(void);
};
void result::display(void)
{
total= part1+part2+score;
put_no();
put_marks();
put_score();
cout<<“total score: “<<total;
}
Abstract Class
• An abstract class is one that is not used
to create objects.
• An abstract class is designed only to act
as a base class i.e. to be inherited by
other classes.
• It is a design concept in program
development and provides a base upon
which other classes may be built.
Order of Constructors and destructors
in derived classes
• Derived-class constructor
– Calls the constructor for its base class first to initialize its
base-class members
– If the derived-class constructor is omitted, its default
constructor calls the base-class’ default constructor
• Destructors are called in the reverse order of
constructor calls.
– Derived-class destructor is called before its base-class
destructor
Order of Constructors in derived
classes
Class B:public A
{ //A() base constructor
}; //B() derived constructor

Class A:public B, public C


{ //B() base first
}; //C() base second
//A() derived
Class A:public B, virtual C
{ //C() virtual base
}; //B() ordinary base
//A() derived
Constructors in derived classes
#include <iostream> Class gamma:public beta, public alpha
Class alpha {
{ int m,n;
Int x; public:
Public: alpha(int i) gamma(int a,float b,int c, int
{x=i; d):alpha(a), beta(b)
cout<<“alpha initialized”;} {
Void show_x(void) m=c;
{ cout<<“x=“<<x;} n=d;
}; cout<<“gamma initialized”;
Class beta }
{ float y; Void show_mn(void)
Public: beta(float j) {
{y=j; cout<<“m=“<<m;
cout<<“n=“<<n;
cout<<“beta initialized”;} }
Void show_y(void) };
{
Cout<<“y=“<<y;
}
};
Constructors in derived classes
int main() Output
{ x=5
gamma y=12.34
g(5,12.34,50,20); m=50
g.show_x(); n=20
g.show_y();
g.show_mn();
return 0;
}
output:
beta initialized
alpha initialized
gamma initialized
Aggregation and Inheritance
• Inheritance
– “Is a” relationship.

• Aggregation
– “has a” relationship
Aggregation and Inheritance
• In general, the difference between
inheritance
and aggregation is the difference between
the
is-a relationship and the has-a relationship.
For example,
– an apple is fruit; thus, you would use
inheritance to model the relationship
between
the classes Apple and Fruit.
– A person has a name; thus, you would
use aggregation to model the
relationship
between the classes Person and Name.
Aggregation
A tire has a circle as its boundary:
class Tire
{
private
String rating;
Circle boundary;
}
Example

• Car is a Vehicle – Inheritance


• Car has a set of Tires – Aggregation
class Car :public Vehicle
{
...
private:
Tire tires[4];
}
Difference
In inheritance, the base class is
referenced ,
not its object.
Aggregation Vs Composition
• In aggregation, the object dob can exist
without the container, the student
object.
• In composition, the contained object can
not exist without the container object.
– Composition can be accomplished using nested
classes i.e. the declaration of one class within
another.
Object Slicing

Class Base Void main()


{ {
protected: Base obj1;
int a,b; Derived obj2; a b
} obj1=obj2; // aa slicebof the
c
members of derived will be
Class Derived: assigned to base class
public base object.
{ c can not be copied into
base class object
int c ; because its not declared in
b
} }
The const keyword
class C
{
const int x;
public: C() : x (5)
{}
};
//The constant keyword needs to be initialized in
the same line…..so we can use initializer list for
that.
8.1 Introduction

• Use operators with objects (operator


overloading)
– Clearer than function calls for certain classes
– Operator sensitive to context
• Examples
– <<
• Stream insertion, bitwise left-shift
– +
• Performs arithmetic on multiple types (integers, floats, etc.)
• Will discuss when to use operator overloading
8.2 Fundamentals of Operator
Overloading

• Types
– Built in (int, char) or user-defined
– Can use existing operators with user-defined types
• Cannot create new operators
• Overloading operators
– Create a function for the class
– Name function operator followed by symbol
• Operator+ for the addition operator +
8.2 Fundamentals of Operator
Overloading

• Using operators on a class object


– It must be overloaded for that class
• Exceptions:
• Assignment operator, =
– Memberwise assignment between objects
• Address operator, &
– Returns address of object
• Both can be overloaded
• Overloading provides concise notation
– object2 = object1.add(object2);
– object2 = object2 + object1;
8.3 Restrictions on Operator Overloading

• Cannot change
– How operators act on built-in data types
• I.e., cannot change integer addition
– Precedence of operator (order of evaluation)
• Use parentheses to force order-of-operations
– Associativity (left-to-right or right-to-left)
– Number of operands
• & is unitary, only acts on one operand
• Cannot create new operators
• Operators must be overloaded explicitly
– Overloading + does not overload +=
8.3 Restrictions on Operator Overloading
8.6 Overloading Unary Operators

• Overloading unary operators


– Non-static member function, no arguments
– Non-member function, one argument
• Argument must be class object or reference to class object
– Remember, static functions only access static data
8.6 Overloading Unary Operators

• Upcoming example (8.10)


– Overload ! to test for empty string
– If non-static member function, needs no arguments
• !s becomes s.operator!()
– class String { public: bool
operator!() const; ... };
– If non-member function, needs one argument
• s! becomes operator!(s)
• class String { friend bool operator!(
const String & ) ... }
8.7 Overloading Binary Operators

• Overloading binary operators


– Non-static member function, one argument
– Non-member function, two arguments
• One argument must be class object or reference
• Upcoming example
– If non-static member function, needs one argument
• class String {
• public:
• const String &operator+=( const String & );
• ...
• };
– y += z equivalent to y.operator+=( z )
8.7 Overloading Binary Operators

• Upcoming example
– If non-member function, needs two arguments
– Example:
• class String {
• friend const String &operator+=(
• String &, const String & );
• ...
• };
– y += z equivalent to operator+=( y, z )
• Reserves memory from a much larger
free store, or heap
• Gives the programmer a pointer to refer
to this memory
There are two types of memory
management operators in C++:
• new
• delete

These two memory management


operators are used for allocating and
freeing memory blocks in efficient and
convenient ways.
The new operator in C++ is used for
dynamic storage allocation. This operator
can be used to create object of any type.
The general syntax of new operator in
C++ is as follows:
pointer variable = new datatype;
In the above statement, new is a
keyword and the pointer variable is a
variable of type datatype.
For example:
int *a=new int;
The new operator allocates sufficient
memory to hold the object of datatype
int and returns a pointer to its starting
point. The pointer variable a holds the
address of memory space allocated.
Dynamic variables are never initialized
by the compiler. Therefore, the
programmer should make it a practice
to first assign them a value.
The assignment can be made in either
of the two ways:
int *a = new int; *a = 20;
or
int *a = new int(20);
Dynamic memory allocation in case of
arrays can be done as following:
int* a = new int[x];
a points to a block of memory
containing x ints
The delete operator in C++ is used
for releasing memory space when the
object is no longer needed. Once a
new operator is used, it is efficient to
use the corresponding delete operator
for release of memory.
The general syntax of delete operator
in C++ is as follows:
delete pointer_variable;

In the above example, delete is a


keyword and the pointer_variable is
the pointer that points to the objects
already created in the new operator.
• The programmer must take care not
to free or delete a pointer variable
that has already been deleted.
• Overloading of new and delete
operator is possible (to be discussed
in detail in later section on
overloading).
• We know that sizeof operator is used
for computing the size of the object.
Using memory management operator,
the size of the object is automatically
computed.
• The programmer must take care not
to free or delete pointer variables that
have not been allocated using a new
operator.
• Null pointer is returned by the new
operator when there is insufficient
memory available for allocation.
#include <iostream.h> void main()
{//Allocates using new operator memory
space //in memory for storing a integer
datatype int *a= new a; *a=100; cout << "
The Output is:a="<<a; //Memory Released
using delete operator delete a;
}
The Output is:a=100
What You Will Learn
• What is polymorphism?

• How to declare and use virtual


functions for abstract classes
Problem with Subclasses
• Given the class hierarchy below
• Consider the existence of a draw function
for each subclass
• Consider also an array of references to
the superclass (which can also point to
various objects of the subclasses)
• How do you specify which draw
statement to be called when using the
references

Shape class hierarchy Shape

Circle Triangle Rectangle

Right Triangle Isosceles Triangle Square


Introduction
• Polymorphism
– Enables “programming in the general”
– The same invocation can produce
“many forms” of results
• Interfaces
– Implemented by classes to assign
common functionality to possibly
unrelated classes
Polymorphism
• Polymorphism enables programmers to deal
in generalities and
– let the execution-time environment handle the
specifics.
• Programmers can command objects to
behave in manners appropriate to those
objects,
– without knowing the types of the objects
– (as long as the objects belong to the same
inheritance hierarchy).
Polymorphism Promotes
Extensibility
• Software that invokes polymorphic
behavior
– independent of the object types to
which messages are sent.
• New object types that can respond
to existing method calls can be
– incorporated into a system without
requiring modification of the base
system.
– Only client code that instantiates new
objects must be modified to
accommodate new types.
Demonstrating Polymorphic
Behavior
• A superclass reference can be
aimed at a subclass object
– a subclass object “is-a” superclass object
– the type of the actual referenced object,
not the type of the reference,
determines which method is called
• A subclass reference can be aimed
at a superclass object only if the
object is downcasted
• View example, Figure 10.1
Polymorphism
• Promotes extensibility
• New objects types can respond to
existing method calls
– Can be incorporated into a system
without modifying base system
• Only client code that instantiates
the new objects must be modified
– To accommodate new types
Abstract Classes and
Methods
• Abstract classes
– Are superclasses (called abstract superclasses)
– Cannot be instantiated
– Incomplete
• subclasses fill in "missing pieces"
• Concrete classes
– Can be instantiated
– Implement every method they declare
– Provide specifics
Abstract Classes and
Methods
• Purpose of an abstract class
– Declare common attributes …
– Declare common behaviors of classes in
a class hierarchy
• Contains one or more abstract
methods
– Subclasses must override
• Instance variables, concrete
methods of abstract class
– subject to normal rules of inheritance
Abstract Classes
• Classes that are too general to
create real objects
• Used only as abstract
superclasses for concrete
subclasses and to declare
reference variables
• Many inheritance hierarchies
have abstract superclasses
occupying the top few levels
Keyword abstract
• Use to declare a class abstract
• Also use to declare a method
abstract
• Abstract classes normally
contain one or more abstract
methods
• All concrete subclasses must
override all inherited abstract
methods
Abstract Classes and Methods
• Iterator class
– Traverses all the objects in a collection, such
as an array
– Often used in polymorphic programming to
traverse a collection that contains references
to objects from various levels of a hierarchy
Abstract Classes
• Declares common attributes and behaviors
of the various classes in a class hierarchy.
• Typically contains one or more abstract
methods
– Subclasses must override if the subclasses are to
be concrete.
• Instance variables and concrete methods of
an abstract class subject to the normal rules
of inheritance.
Beware! Compile Time Errors

• Attempting to instantiate an object of an


abstract class
• Failure to implement a superclass’s abstract
methods in a subclass
– unless the subclass is also declared abstract.
Creating Abstract Superclass
Employee
• abstract superclass Employee, Figure 10.4

– earnings is declared abstract


• No implementation can be given for earnings in the
Employee abstract class
– An array of Employee variables will store
references to subclass objects
• earnings method calls from these variables will call the
appropriate version of the earnings method
Example Based on
Employee
Abstract Class

Concrete
Classes

Click on Classes to see source code


Polymorphic interface for the
Employee hierarchy classes.
Superclass And Subclass
Assignment Rules
• Assigning a superclass reference to
superclass variable straightforward
• Subclass reference to subclass variable
straightforward
• Subclass reference to superclass variable
safe
– because of is-a relationship
– Referring to subclass-only members through
superclass variables a compilation error
• Superclass reference to a subclass
variable a compilation error
– Downcasting can get around this error
final Methods and
Classes
• final methods
– Cannot be overridden in a subclass
– private and static methods implicitly
final
– final methods are resolved at compile
time, this is known as static binding
• Compilers can optimize by inlining the code
• final classes
– Cannot be extended by a subclass
– All methods in a final class implicitly
final
Why Use Interfaces
• Java has single inheritance, only
• This means that a child class
inherits from only one parent class
• Sometimes multiple inheritance
would be convenient
• Interfaces give Java some of the
advantages of multiple inheritance
without incurring the
disadvantages
Why Use Interfaces
• Provide capability for unrelated
classes to implement a set of
common methods
• Define and standardize ways
people and systems can interact
• Interface specifies what operations
must be permitted
• Does not specify how performed
What is an Interface?

• An interface is a collection of
constants and method declarations
• An interface describes a set of
methods that can be called on an
object
• The method declarations do not
include an implementation
– there is no method body
What is an Interface?
• A child class that extends a parent
class can also implement an
interface to gain some additional
behavior
• Implementing an interface is a
“promise” to include the specified
method(s)
• A method in an interface cannot be
made private
When A Class Definition
Implements An Interface:
• It must implement each method in
the interface
• Each method must be public (even
though the interface might not say
so)
• Constants from the interface can
be used as if they had been
defined in the class (They should
not be re-defined in the class)
Declaring Constants with
Interfaces
• Interfaces can be used to declare
constants used in many class
declarations
– These constants are implicitly public,
static and final
– Using a static import declaration
allows clients to use these constants
with just their names
Implementation vs. Interface
Inheritance
Implementation Interface Inheritance
Inheritance • Functionality lower in
• Functionality high in hierarchy
the hierarchy • Superclass specifies
• Each new subclass one or more abstract
inherits one or more methods
methods declared in • Must be declared for
superclass each class in
• Subclass uses hierarchy
superclass • Overridden for
declarations subclass-specific
implementations
Creating and Using
Interfaces
• Declaration begins with interface
keyword
• Classes implement an interface
(and its methods)
• Contains public abstract methods
– Classes (that implement the interface)
must implement these methods
Creating and Using
Interfaces
• Consider the possibility of having a
class which manipulates
mathematical functions
• You want to send a function as a
parameter
– Note that C++ allows this directly
– Java does not
• This task can be accomplished with
interfaces
POLYMORPHISM
• Polymorphism means many (poly) shapes
(morph)
• It can be defined one interface multiple
methods which means that one interface can
be used to perform different but related
activities.
• It is achieved by two ways:
• Overloading
• Overriding
Run time(Dynamic)Polymorphism
• In this dynamic binding is performed
• In dynamic binding the decision regarding the
selection of appropriate function to be called
is made by compiler at run time.
• This is because the information pertaining to
the selection of appropriate function
definition corresponding to a function call is
known only at the run time.
• It is also called the late binding as the
compiler delays the binding decision until run
time.
• The advantage is that it allows greater
flexiability by enabling user to create class
libraries that can be reused and extended as
per requirement
• The disadvantage is that there is little less od
execution speed as compiler will have to
perform certain overheads at run time
VIRTUAL FUNCTIONS

• A virtual function is a member function


declared in the base class using the keyword
virtual whose functionality is redefined(same
function name) by its derived classes.
• The virtual function declared in the base class
represent the single interface and its
redefinition by the derived classes
implements operations specific of each
derived class
• To implement run time polymorphism using
virtual function ,it must be invoked through
the base class pointer that can contain the
address of objects of different derived
classes.
• When the virtual function is invoked through
the base class pointer the compiler chooses
the appropriate member function of the
derived class at run time depending upon the
contents of base class pointer and not the
type of pointer.
• Thus by making the base class pointer
pointing to objects of different classes ,the
different versions of virtual functions can be
called at run time
PURE VIRTUAL FUNCTIONS

• A virtual function is defined inside the base


class and redefined in the derived classes.
• But in most situations,a virtual function
defined in the base class does not have any
meaningful operation for it to perform.
• A better way to change the virtual function
cal_area() in the base class is:
virtual void cal_area() =0;
• The above statement is not an assignment
statement but it’s a way to inform the
compiler that the function has no body.
• Such a virtual function having initializer=0 in
its declaration and which does not provide
any implementation (no body) is known as
pure virtual functions.
• A pure virtual function is also known as
dummy functions or do nothing function.
they serve merely as an interface to be
overridden by subsequent derived classes
Virtual Destructor

• Destructor can also be declared as virtual


• If we want to create an object of a derived
class dynamically using the base class pointer.
If we destroy this derived object with
non-virtual destructor explicitly using the
delete operator in association with the base
class pointer then only the destructor of the
base class is executed and not the derived
class’s destructor .
this pointer
• Every object has a special pointer "this" which
points to the object itself.
• This pointer is accessible to all members of
the class but not to any static members of the
class.
• Can be used to find the address of the object
in which the function is a member.
• Presence of this pointer is not included in the
sizeof calculations.
Object Slicing

• Object slicing is a concept where additional


attributes of a derived class object is sliced to
form a base class object.
• Object slicing doesn't occur when pointers or
references to objects are passed as function
arguments since both the pointers are of the
same size.
• Object slicing will be noticed when pass by
value is done for a derived class object for a
function accepting base class object.
• Object slicing could be prevented by making
the base class function pure virtual there by
disallowing object creation.
Exception Handling
Exception Handling
•Exception Handling Basics
•Exception Handling mechanism
•Throwing Exception
•Catching exception
•Rethrowing Exception
•Exception Specification
Exception Handling

• Exception Handling
• Exception are the errors that occur at run
time and can stop the working of the
program abruptly.
• They can occur in various situations- one
such condition when the number is divided
by 0.
• For handling such exceptions we have an
error handling mechanism called as
exception handling.
Objective

• Main objective is to provide a way to


detect and report the exception
condition so that necessary action can be
taken without troubling user
Exception handling mechanism
• When exception occurs the portion of
program that detects the exception can
inform that exception have occurred by
throwing it.
• When we throw an exception, program
control immidiately stops the step by step
execution of code and jumps to exception
handler.
• Exception handler catches the exception and
process it without troubling user
• When there is no exception
handler,program terminates abruptly.
Exception Specification

• There is a list of exceptions that function can throw.


This specification is known as exception specification
or throw list.
• It ensures that function will not throw other than
listed exceptions in exception specification.
• Syntax:
Data_type function_name(para_list) throw(type_list)
{
//function_body
}

You might also like