0% found this document useful (0 votes)
43 views217 pages

XII C++ Jul 2023

All of this documents are my classroom notes

Uploaded by

Aaryan Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views217 pages

XII C++ Jul 2023

All of this documents are my classroom notes

Uploaded by

Aaryan Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 217

C++

MRS. MRUNALINI. S. HIRPATHAK


XII Computer Science.

1
C++
• C++ is Object Oriented programming
language.

• Developed by Bjarne Stropstrup.

• Its incremented version of C.

2
Advantages of C++

•Incremented versions of C

•Important features are

• Classes
• Object
• Function overloading
• Operator overloading

3
Advantages of C++ contd…..
• Object oriented libraries can be build
• C++ programs can be easily implemented ,
maintained, expanded
• Can create abstract data to inherit properties of
existing data type
• C++ supports polymorphism
• Real life system can be build using C++
• eg:-
•editor
•compilers
•Data base communication systems
4
Limitations of procedure oriented programs

•Problem is viewed as sequence of


events
•Focus on functions not on data
•Data flows freely in the program
•Data global therefore no data security
•Single change disrupts t complete
system therefore many bugs
5
Features of OOPS
•Emphasis on data, not procedure.
•Programs are divided into number of object
•Data structure is divided such that it
characterizes objects.
•Function operate on data
•Data is hidden and cannot be accessed by
external functions

6
Features of OOPS (contd…...)

•Objects my communicate with each


other through functions.

•New data and new functions can be


easily added whenever needed.

•Follows a bottoms up approach


7
Difference
POP OOPS

• SEQUENCE OF EVENTS • PROB IS DIVIDED INTO NUMBER OF


READ , CALCULATE, PRINT ENTITIES CALLED OBJECTS

• EMPHSIS ON PROCEDURE • EMPHSIS ON DATA

• LARGE PROBLEM DIVIDED INTO • PROGRAM DIVIDED INTO OBJECTS


FUNCTIONS
• DATA IS HIDDEN FROM EXTERNAL
• DATA FLOWS FREELY FUNCTIONS

• TOP DOWN APPROACH • BOTTOM UP APPROACH

8
Concepts of OOPs

• Objects
• Classes
• Inheritance
• Polymorphism
• Data abstraction and data encapsulation
• Dynamic binding
• Message passing
• Exception handling

9
XI review

• TOKENS - The smallest individual unit in a program are known as


tokens.

C++ has following tokens:

• Keywords
• Identifiers
• Constant
• Operator

10
• Keywords : These are explicitly reserved and cannot
be used as names of program variables.
eg: int void etc

• Identifiers : theses are names of variables, functions,


arrays, classes etc. Created by the programmers
Rules of Identifiers
➢ should start with an alphabet
➢ cannot start with a digit
➢ uppercase and lower case are distinct.
➢ keyword cannot be used.

11
• Constants : Constants refers fixed values that
do not change during the execution of the
program.

Two ways of creating constants


1. Using the qualifier constant
const float pi = 3.14156;
The value of pi will not change
through out the course of program

12
2. Defining the set of inter constants using enum

a. enum {x, y, z}
will assign x=0, y = 1, z = 2
b. enum {x= 200, y = 20, z= 2}
c. enum {x= 20, y, z} // y = 21, z=22
d. enum {true, false} //true =0, false = 1

13
Basic Data types in C++
•Build in
• Void
• Integral eg int char
• Floating eg float double
•User defined
• Structure
• Union
• Class
• Enumeration
•Derived
• Arrays
• Functions
• pointers 14
Operators
1. Arithmetic
• + +=
• - -=
• * *=
• / /=
• %
2. Logical
• &&
• //
3. Unary
• -
4. Assignment
• =
15
Operators contd…

1. :: - Scope resolution operator


2. << - insertion operator
3. >> - extraction operator
4. :: * - pointer to member operator
5. -> - pointer to member operator
6. .* - pointer to member operator
7. delete - memory release operator
8. new - memory allocation operator

16
Operators contd…

9. endl - line feed operator


10. setw - field width operator
11. * - dereferencing
12. & - address of operator
13. conditional operator ?:
14. relational operator
1. ==
2. !=
3. <=
4. >=
5. >
6. <
17
<< insertion operator (put /output operator)

• It inserts or sends the contents on its right to the


object on its left.

eg :
cout <<“enter the value of a ”;

<< will put /insert the string on the screen

18
>>extraction operator (get op/input op)

• It inserts or sends the contents on its right to the object on its left.
eg:

cin>>a

>> will extract a value from keyboard and give it to ‘a’.

19
new operator

• The new operator obtains memory block from OS and


returns a pointer to its starting point.

Returns a null value if memory allocation is unsuccessful

Delete
The delete operator is used to return the memory allocated
by new operator back to its memory pool
(which can b used for other part of the program )

20
new and delete operators

void main()
{
char *str = “hello!”;
int len = strlen(str);
char *ptr;
ptr = new char[len +1];
cout <<“ ptr = ”<<ptr;
delete ptr;
}
21
Scope resolution operator ::
C++ is a block structured language
If we have one block inside the other block……
{
int x =10;
{
int x =20; block 2
cout<<“inner block”<<x;
cout<<“outer block”<<x; block 1
}
} here block 2 is inside block 1,
The declaration of the variable ‘ x’ in inner block is the
same as in outer block.
OUTPUT
This is allowed in C++. Inner block 20
Outer block 20 22
Scope resolution operator :: contd…...
Scope resolution operator Is used to uncover the hidden variables.
{
int x =10;
{
int x =20;
cout<<“inner block”<<x; block 2
cout<<“outer block”<< :: x; block 1
}
}
OUTPUT
Inner block 20
Outer block 10 23
Control structures in C++

• Sequential
• Selective -
1. if
2. else if
3. nested if
4. switch…… case
• iterative
1. for
2. while
3. do …. while

24
Programs
• Write a program in C++ to check if the given alphabet is a vowel or
not using switch case.

• Write a program in C++ to find the largest number in 3 given


numbers using conditional operator.

• Write a program in C++ to find the factorial of a given number using


function. …..
double fact(int);
• Write a program in C++ to check if the given number is a prime
number .

25
Wap in C++to find factorial of a given number
# include<iostream.h>
# include<conio.h>
void main()
{ int i =1, fact =1,n;
clrscr() ;
cout<<“ enter the number for which u want to find the factorial”;
cin >>n;
while( i<n)
{
fact = fact *i;
i++;
}
cout<<“ factorial of a given number is = “<<fact;
getch();
}
26
Write a program in C++ to check if the given alphabet is a
vowel or not using switch case.
# include<iostream.h>
# include<conio.h>
void main()
{
char ch ;
clrscr() ;
cout<<"Enter the alphabet" ;
cin>> ch ;
switch(ch)
{
case ‘a’:
case ‘e:
27
case ‘i’:
case ‘o’:
case ‘u’:
case ‘A’:
case ‘E’:
case ‘I’:
case ‘O’:
case ‘U’: cout<<“ it’s a vowel”;
break;
default: cout<<“it’s a consonent”
}
getch();
}

28
Program to find if the year is leap year or not using if else

#include<iostream.h>
#include<conio.h>
void main()
{ int yr ;
clrscr();
cout<<"Enter the year";
cin>>yr;
if(yr%4 == 0)
{
cout<<“It’s a leap year”;
}
else
{
cout<<" It’s a leap not a year”;
} 29

getch();
}
Write a program in C++ to check if the given number is a prime
number
#include<iostream.h>
#include<conio.h> if ( f==0)
int main() {
cout<<“ it’s a prime number”;
{ }
int i =2, n, f= 0; else
{
clrscr();
cout<<“ it’s not a prime number”;
cout << “Enter the number to }getch();}
be checked”;
cin>>n;
while (i<n)
{ if (n%i == 0)
{ f = 1;
break;
}
i++;
}

30
Functions in C++

• Syntax

return_type function_name (argument_list)


{

31
Steps include

• Function prototype/ declaration

• Function call

• Function definition

32
Function overloading

• Same function name


• Different argument list
• Return type does not matter
Eg.
void area();
void area(int );
void area(int, int);
void area(int, float);
void area(float);
int area (float) ;// not allowed

33
Inline function
• A function that can be expanded inline when its invoked.
• syntax
inline function_name(args)
{

}
• All inline function must be defined before they are called.

34
Inline function contd…

• inline is a keyword

•It sends a request and not a command to the


compiler.

•The compiler decides if the function can be


made inline or not.

35
Why Inline function ……
• Lots of time is wasted when the function jumps from
calling function to the called function and back.

• Similarly memory is also wasted in such jumps.

• Especially when the functions are small such


overheads are very time consuming.

• inline function is expanded when its invoked.

• Therefore it helps in faster execution of the programs

• And saves memory space.

36
When inline request will be rejected

• Functions with loops….. ie for, while etc

• Functions with if , switch, goto …

• Functions with static variables.

• Recursive functions

• large functions.

37
Default arguments
• Function assigns default values to the parameter value
which does not have a matching arguments in
function call

• default value are specified when the function is


declared
ie. In function prototype

• only the trailing arguments can have the default


arguments.

38
Default arguments contd……
float amount (float p, int period, float rate= 1.5)
above prototype declares 0.15 to the value rate
So the function call…..
➢ value = amount (5000, 7)
will pass…… p = 5000
period = 5
And rate = 0.15
BUT
➢ value = amount (5000, 5, 2.5)
p = 5000
period = 5
And rate = 2.5

39
Advantages of Default arguments
➢ Useful in situation when some arguments have same
values.

➢ It provides better flexibility to program allowing us to


use particular argument that are meaningful to a
particular situations.

➢ use default arguments to add parameters to exiting


function.

➢ default arguments can be combine similar functions


into a single unit.
40
Arrays in C++

➢ Identical/ homogeneous data


➢Continuous memory locations
➢Under the same name.

➢Syntax ; storage_class array name


eg:- int arr[10] ;
array of 10 integers stored in consecutive memory location.
arr[0] ----- first element
arr[9] ------ last element

41
Bubble sort
#include<iostream.h>
#include<conio.h>
void print(float a[], int n);
void sort(float a[], int n);
int main()
{
float a[]={22,45,58,90,23,32,2,67,30,17};
int size=sizeof(a)/sizeof(float);
clrscr();
cout<<"Output\n";
cout<<"Unsorted array:="<<endl;
print(a,size);
sort(a,size);
cout<<"\n Array elements after sorting:="<<endl;
cout<<"\t\t";
print(a,size);
getch();
return 0;
}

42
void sort(float a[],int n)
{ for(int i=1;i<=n;i++)
{
for(int j=0;j<n-i;j++)
{ if(a[j]>a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}}}}
void print(float a[],int n)
{ int i;
cout<<"\t\t";
for(i=0;i<n;i++)
cout<<a[i]<<",";
}

43
Program for Fibonacci series
# include <iostream.h>
# include <conio.h>
void main()
{ clrscr();
int f0=0,f1=1,f2,n,i ;
cout<<"enter the number";
cin>>n;
cout<<"the fib series is "<<f0<<"\t"<<f1<<"\t";
for(i = 3; i<=n ;i ++)
{ f2 = f0+f1;
cout<<f2<<"\t";
f0 = f1;
f1= f2;
} getch();
}

44
Reversing the given string
#include<iostream.h>
#include<conio.h>
#include<string.h>
int main()
{ char str[80];
int n=0;
void reverse(char*,int);
cout<<"Enter the string:=";
cin.getline(str,80); //To read a line of text
cout<<"\n The string is:=\t"<<str;
n=strlen(str);
reverse(str,n);
cout<<"\n The reverse string is:=\t"<<str;
return 0;
} 45
void reverse(char *s,int n)
{
char *e=s+n;
char temp;
while(s<e-1)
{
--e;
temp=*e;
*e=*s;
*s=temp;
s++;
}
}

46
A1.4 Traverse the array of 5 real numbers with a pointer. Print the size in bytes of the datatypes
of the array elements, sum of array elements and their corresponding memory address.

• #include<iostream.h> for(float *p=a;p<e;p++)


#include<conio.h> {
sum+=*p;
int main() cout<<"\tp="<<p<<endl;
{ float a[]={10,25,32,69,85}; cout<<"\t*p="<<*p<<endl;
clrscr(); cout<<"\tsum="<<sum<<endl;
cout<<"Starting address of the }
array :="<<a<<endl; cout<<"end address of the array
cout<<"size of array :="<<e<<endl;
elements:="<<sizeof(float)<<endl; getch();
float *e=a+5; return 0;
float sum=0; }
47
Write a C++ program to accept a string from keyboard and copy string into another
string without using library function.
# include<iostream.h>
# include<conio.h>
void main()
{ clrscr() ;
char src[20], dest[20];
int i=0, cnt =0;
cout<<”enter the string”;
cin.getline(src, 20);
while(src[i] != ‘\n’)
{ cnt++;
i++;
}
for(i =0; i<=cnt ; i++ )
{ dest[i] = src[i];
}
write(dest, cnt);
write(src, cnt);
getch();
} 48
Program for palindrome
# include <iostream.h>
# include <conio.h>
void main()
{ int n, dn, temp = 0, d;
cout<<“enter the number”;
cin>>n;
dn = n;
while (dn ! = 0)
{ d = dn%10;
temp = (temp *10)+d;
dn = dn/10;
}
if ( n == temp)
cout <<“ the number is a palindrome”;
else
cout <<“ the number is not a palindrome”
}
49
Program for amstrong number
# include <iostream.h>
# include <conio.h>
void main()
{ int n, dn, temp = 0, d;
clrscr();
cout<<“enter the number”;
cin>>n;
dn = n;
while (dn ! = 0)
{
d = dn%10;
temp = temp +(d*d*d);
dn = dn/10;
}
if ( n == temp)
cout <<“ the number is a amgstrong number”;
else
cout <<“ the number is not an amgstrong number”;
}
50
Program for recursive function
# include <iostream.h>
# include <conio.h>
int rec(int);
void main()
{ int a, fact;
cout<<“enter the number”;
cin>>n;
fact = rec(a) ;
cout<<“factorial of the given number is ”<<fact;
}
int rec (int x)
{ int f;
if ( x ==1)
return 1;
else
f = x * rec(x-1);
return 1;
} 51
Recursive functions
# include <iostream.h> int func2(int x )
# include <conio.h> {
int func1 (int); int y, z;
int func2 (int); y = func3(x-1);
int func13(int); z = y * x;
int func14(int); return z;
void main() }
{ int A = 4, B; int func3(int x )
B = fun1(A); {
cout <<B; int y, z;
} y = func4(x-1);
int func1(int x ) z = y * x;
{ int y, z; return z;
}
y = func2(x-1);
int func4(int x )
z = y * x;
{return 1;
return z;
} }
52
Pointers in C++

• Pointer is a variable

• Points to a memory location

• * is operator used to identify a pointer


•Eg: int I, *ptr;

53
Pointers in C++ contd……

int a, *aptr ;
Output
• cout<<a ;
• cout<< & ; a = 20
• cout<< aptr ; & a = 2000
• cout<< &aptr;
aptr = 2000
&aptr = 4000
a aptr
* aptr =
20 2000
2000 4000
54
Advantages of pointers
➢It allows us to pass variables, arrays , strings, structure as function
argument

• It supports dynamic allocation and de-allocation of memory

• Swapping is possible without physically moving the variable.

• Allows to establish link between data elements and objects

• Pointers allows to return structure variable.

55
Pointer arithmatics contd…….

• ptr++ - it uses the original value of ptr and then the ptr is incremented
after statement execution.
ptr = ptr + sizeof(data_type)
• ++ptr - original pointer is incremented before statement execution.
ptr = ptr + sizeof(data_type)
• ptr-- - it uses the original value of ptr and then the ptr is decremented
after statement execution.
ptr = ptr - sizeof(data_type)
• --ptr - original pointer is decremented before statement execution.
ptr = ptr - sizeof(data_type)

56
Pointer arithmatics
a[0] a[1] a[2] a[3] a[4]

10 20 30 40 50
2000 2002 2004 2006 2008

•* (++ptr) - it increments the pointer and then retrieves the contents of


the memory location pointed by pointer.

• (*ptr)++ Increments contents of location pointed by pointer.

• Also ++(*ptr), --(*ptr), (*ptr)--

57
Reference feature of C++

•Reference can be used as

• A function parameters
• As a return value
• A stand alone reference

58
1. Referance variable as parameter

void minus (int &i);


void main() OUTPUT
{int x =10; X = 10
X = -10
cout<<x;
minus(x);
cout<<x;
Here Y becomes alias for
}
void minus(int &y)
whatever argument for
{ minus function.
y = -y;
}
And whatever changes
are made in minus are
reflected back in main.
59
2. Referance variable as return type.

A function can also return a reference

Eg: if (x>y)
return &x;
else
return &y;

60
3. Referance variable as stand alone ref.

We can create independent reference variable.


They must be initialised at the point of declartion.
eg:
float total = 100;
float &sum = total;

total/sum

100
2000

Whatever changes are made in sum, they will be reflected back


in total.

61
Pointers contd…...

• Call by value

• Call by reference

➢ using reference variables

➢ using pointers

62
Program swap using call by value
#include<iostream.h> void swapv(int x,int y)
#include<conio.h> {
void main()
int temp;
{
void swapv(int, int); cout<<"\n value of x and y
before swapping
int a,b;
"<<x<<"\t"<<y;
clrscr();
temp=x;
cout<<"\n Enter a and b";
cin>>a>>b; x=y;
swapv(a, b); y=temp;
cout<<"\n Value of a and b cout<<"\n Value of x and y
after swapping after swapping
"<<a<<"\t"<<b;
"<<x<<"\t"<<y;
getch();
} }
63
Program swap using call by referrence using poiters

#include<iostream.h> void swapp(int * x , int * y)


#include<conio.h> {
void main() int temp;
{ cout<<"\n value of x and y
void swapp(int*, int*); before swapping
"<<x<<"\t"<<y;
int a,b;
clrscr();
temp=*x;
cout<<"\n Enter a and b";
*x=*y;
cin>>a>>b;
*y=temp;
swapp(&a,& b);
cout<<"\n Value of a and
b after swapping cout<<"\n Value of x and
"<<*a<<"\t"<<*b; y after swapping
"<<*x<<"\t"<<*y;
getch();
}
} 64
Program swap using call by referrence using reference
variables
#include<iostream.h> void swapr(int &x,int &y)
#include<conio.h> {
int temp;
void main()
cout<<"\n value of x and y before
{ void swapr(int& , int&); swapping "<<x<<"\t"<<y;
int a,b;
clrscr(); temp=x;
x=y;
cout<<"\n Enter a and b";
y=temp;
cin>>a>>b;
swapr(a, b); cout<<"\n Value of x and y after
cout<<"\n Value of a and b after swapping "<<x<<"\t"<<y;
swapping "<<a<<"\t"<<b; }
getch();
}
65
String functions in C++

•strlen
void main()
{
char arr[] =“Hello!”;
int len1, len2;
len1 = strlen(arr);
len2 = strlen(“hi!”)
cout<<len1;
cout<<len2;
}
66
String functions in C++ ontd…..

•strcpy
void main()
{ char src[] =“Hello!”;
char dest[] =“welcome!”;
strcpy(dest,src);
cout<<src<<dest;
} Output
src = Hello!
dest = Hello!
67
String functions in C++

•strcat
void main()
{ char src[] =“Hello!”;
char dest[] =“welcome!”;
strcat(dest,src);
cout<<src<<dest;
Output
} src = Hello!
dest = WelcomeHello!
68
String functions in C++ contd…..

•strcmp
void main()
{ char s1[] =“ABC”;
char s2[] =“XYZ”;
i= strcmp(s1, “ABC”);
j= strcmp(s1, s2);
cout<<i<<j; Output
} i=0….......... True
j= 23 ………….false
69
Classes :

• Classes are a way with which you can


bind the data and its associated
functions together. These are user
defined data type and behave as built
in data type.
•Private members can be accessed by
only other member functions of that
class.
•Public members can be accessed from
outside the class.
•Objects are variables of the type class
70
General form of class declaration
class classname /* start of class*/
{
private:

member variables or data member;


member function;

public:

member variables or data member;


member function;
}; /* end of class

71
Visibility labels

•Private
•Public
•Protected

72
Classes contain

•Data members
eg: int, float, char

•Member functions
void fun();

73
Memory allocation in a class
Data members : copy of data members is given to all the objects.
Member functions are shared
Eg:
class A
{
int var1, var2; fun1 fun2
Fun1(){}
Fun2(){}
};
void main()
{ obj2 obj3
obj1 obj4
A obj1,obj2,obj3,obj4;
obj1.fun1();
obj1.fun2(); var1 var1 var1 var1
obj2.fun1(); var2 var2 var2 var2
obj2.fun2();
..
} 74
Defining a member function

• Inside class definition

• Outside class definition

75
Functions inside the class
#include<iostream.h>
#include<conio.h>
class student void main()
{ {
int roll_no;
public:
student s;
get_roll() s.get_roll();
{ s.put_roll();
cout<<“enter your roll no”;
cin>>roll_no;
}
}
put_roll()
{
cout<<“roll no is”<<roll_no;
}
};
76
Functions outside the class
#include<iostream.h> void student :: put_roll()
#include<conio.h> {
class student cout<<“roll no
{ int roll_no; is”<<roll_no;
public:
void get_roll();
}
void put_roll();
}; void main()
void student :: get_roll() {
{ student s;
cout<<“enter your roll no”;
s.get_roll();
cin>>roll_no;
} s.put_roll();
}
77
Eamples
#include<iostream.h> void main()
#include<conio.h> { int n;
float p;
class inventory cout<<“enter the number of items
selected”;
{ int no;
cin>>n;
float cost; cout <<“enter price”;
public: cin>> p
void geti (int a, float b) inventory I;
{ n0 = a; I. geti(n,p);
cost = b; I.puti();
}
}
void puti ()
{ cout<<“Total price =
”<<(cost *no);
}}; 78
Examples
#include<iostream.h> while(num != den)
{
#include<conio.h>
if(nu>den)
class gcd
num = num – den;
{int num, den;
else
public:
den = den – num;
void find ();
}; }
void gcd :: find () cout<< num;
{ }
cout << “enter numerator”;
cin>>num; void main()
cout <<“enter {
gcd g;
denomenator”; g.find();
cin >>den; }

79
Examples
#include<iostream.h>
#include<conio.h> void main()
class fact {
{int n, f; cout << “enter the
public: number”;
void find (int );
}; cin>>n;
void fact:: find (int a)
{ int i = 1; fact f1;
n=a; f1.find(n);
f = 1;
while (i< n)
{ }
f = f*i;
i++;
}
cout <<“factorial of the given
number is”<<f;
} 80
Program with functions in class
# include<iostream.h> void Ratio :: assign(int n, int d)
# include<conio.h> { num = n;
class Ratio den = d;
{ private:
}
int num,den; double Ratio :: convert()
public:
{
void assign(int, int);
return (double)num/den;
double convert();
}
void invert();
void Ratio :: invert ()
void print();
{ int temp;
};
temp = num;
void Ratio :: print ()
num = den;
{ cout <<"Ratio is = "
<<num<<"/"<<den; den = temp;
} }
81
Program with functions in class contd……..

void main()
{
clrscr();
Ratio x;
x.assign(22,7);
x.print();
cout<<"converted ratio is = "<< x.convert()<<endl;
x.invert();
x.print();
getch();
}

82
Storage class

1. Automatic (local) 1. Initialized to garbage values.


2. Can be initialized to any
value.
void main() 3. Life is from the point of
{ declaretion to the end of the
int i , j ,k; block.
4. Keyword is auto
float p, q, r;
} Eg: auto int I;
(by default auto thus no need to
mention)
Storage class

1. Initialized to garbage values.


2. External (global) 2. Can be initialized to any value.
3. Life is from the point of
int m, n; declaretion to the end of the
Program
void main()
4. Keyword is extern.
{
int i , j ,k; Eg: extern int I;
float p, q, r;
} (by default extern thus no need
to mention)
Storage class

1. Initialized to ZERO
2. Static (local and global)
2. Can not be initialized to
any other value.
Static local 3. Life is from the point of
declaration to the end of the
Program.
void main() (though it is not seen outside
{ the block)
static int S; 4. Keyword is static.
int i , j ,k;
float p, q, r; Eg: static int I;
( only one copy is created)
}
Storage class

2. Static (local and global) 1. Initialized to ZERO

2. Can not be initialized to any


Static global
other value.

static int S; 3. Life is from the point of


void main() declaration to the end of the
Program.
{
4. Keyword is static.
int i , j ,k;
float p, q, r; Eg: static int I;
( only one copy is created)
}
Storage class

3. Register A, B, C ,D, H, L
Static data members

class test
{
static void getdata();
}
Following characteristics

1. It is initialized to a zero when the first object of its class is


created. (no other initialization is permitted ).
2. 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 object are possible.)
3. It is visible only for that class, but its life is throughout the
program.

88
Static member function
class counter void main()
{
{
counter c1, c2,c3;
int count;
static int s ; c1.increment();
c1.increment();
public:
counter () c1.increment();
{
}
count = 0;
}
void increment()
{ c1 c1 c1
count = 0 count = 0 count = 0
count ++;
s=0 s=1 s=2
s++;
}}:
After inc After inc After inc
func call func call func call

count =1 count =1 count =1


s =1 s =2 s =3
Static data members

• class test
•{
static void getdata();
}
• Following characteristics
1. It is initialized to a zero when the first object of its class is
created. (no other initialization is permitted ).
2. 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 object are possible.)
3. It is visible only for that class, but its life is throughout the
program.

90
Static data members

static variable are normally used to maintain values common to the


entire class
eg counter

class integer
{
static int count;
}

Static data members are stored separately rather than as a part of an


object

91
Static member function

Static member function have following properties


• a static function can have access to only other static members
(functions and variables) which are declared in the same class.

• static member function can be called using class_name instead of its


object.

class test
{
static void get();
}
test.get();

92
Constructors :
Constructors are special member functions whose
task is to initialize the objects of its class. The constructor is
invoked when an object of its associated class is created.
Constructors have same name as that of the class name.

Syntax:
class class-name
{ …………
public :
class-name(); [Constructor]
………..
…………
};

93
Example of constructor
E.g.
class integer
{ int m,n;
public:
integer ( )
{m = 1;
n =2; } //default constructor
integer (int x, int y) //parameterized constructor
{ m= x;
n =y;
}
94
};
//Program for constructon (default and parameterized)

#include<iostream.h> void display()


{
#include<conio.h> cout<<"ratio="<<num<<
"/"<<den;
class ratio }};
{ int num,den; void main()
public: {
clrscr();
ratio() ratio x;
{ num=0; ratio z(10);
den=1; cout<<"\nratio
x=";
} x.display();
ratio(int x) cout<<"\nratio
z=";
{ num=x; z.display();
den = 1 getch();
} }
95
Characteristics of A constructor

1. The constructor functions have same name as


that of class name.

2. They should be declared in the public section.

3. They are invoked automatically when the objects


are created.

4.They do not have return types not even void and


therefore cannot return any values. 96
Characteristics of A constructor

5. They cannot be inherited, though a derived class can

call the base class constructor.

6. Like C+ + functions they can have default arguments.

7. Constructor cannot be virtual

8. They make implicit calls to the operators new and

delete.

97
Destructor:

Destructor is a function that


automatically executes when an object is
destroyed.
The primary aim of destructor is to
release the space or memory on a heap.
A destructor function can be invoked
explicitly.
A destructor name is same as that of the
class name preceded with the ~( Tilde ) sign.
Destructor do not take any arguments
nor do they return any value.
98
Syntax:
class class-name
{ …………
public :
~class-name(); [destructor]
………..
…………
};

Eg;
class integer
{…………
public:
~integer ( ) { } //destructor
…………
};
99
Program for constructor and destructor
#include<iostream.h>
#include<conio.h>
class Ratio
{
int n,d;
public:
Ratio()
{ n=0;
d=1;
cout<<"Object is now born"<<endl;
}
void print()
{ cout<<"ratio is = "<<n<<"/"<<d;
cout<<"the object is still alive"<<endl;
}

100
~ Ratio()
{
cout<<"Object is dead"<<endl;
}
};

void main()
{
{
Ratio r;
r.print();
}
getch();
}

101
Fibonacci series using constructor
# include<conio.h>
# include<iostream.h>
class Fibonacci
{ unsigned long int f2,f0,f1;
public:
Fibonacci();
void calculate();
void display();
};
Fibonacci :: Fibonacci ()
{ f0 =0;
f1 = 1;
cout<<“The fibonacci series is ”<<f0<<“ , “<<f1<<“ , ”;
}

102
void Fibonacci :: calculate()
{
f2 = f0+f1;
f0 = f1;
f1 = f2;
}
void Fibonacci :: display()
{cout<<f2<<“ , ”;
}
void main()
{ Fibonacci x;
for(int i = 3; i<=15 ; i++)
{x.calculate();
x.display();
}}

103
ARRAY OF OBJECTS
We can have array of variables which are of type
class. Such variables are called as array of objects. An
array of objects behaves like any other array, we can
use the usual array-accessing methods to access the
individual elements and then the dot member
operator to access the member function.
class emp
{----
-----
};
main()
{
………
emp eobj[10]; /* array of 10 emp objects*/
}
104
Program to implement array of objects
#include<iostream.h>
#include<conio.h>
class circle
{
private:
int x, y;
float r,a,circum;
public:
circle() //default constructor
{
x= 0;
y=0;
r=0;
}
void get_data();
void put_data();
float area();
float circumference();
};
105


void circle::get_data()
{ cout<<"\nEnter the x co-ordinate=";
cin>>x;
cout<<"Enter the y-co-ordinate=";
cin>>y;
cout<<"Enter the radius=";
cin>>r;
}
void circle::put_data()
{
cout<<"\n co-ordinates of circle "<<"are ("<<x<<","<<y<<")";
cout<<"\n radius is="<<r;
cout<<"\n area is="<<area();
cout<<"\n circumference="<<circumference();
}
float circle::area() //area function
{ a=3.14*r*r;
return a;
}
float circle::circumference() //circumference function
{ circum=2*3.14*r;
return circum;
} 106
void main()
{ const size=2;
circle c[size]; //Array of circle class object
int i;
cout<<"\n Default values:-";

for (i=0; i<2; i++)


{ cout<<"\n circle:: "<<i+1;
c[i].put_data();
cout<<endl;
}

for (i=0; i<2; i++)


{ cout<<"\n circle:: "<<i+1;
c[i].get_data(); //get co-ordinates of circle
}

for (i=0; i<2; i++)


{ cout<<"\n circle:: "<<i+1;
c[i].put_data();
cout<<endl;
}
}

107
• write a program in C++ to read rollno , marks in p, c, m of 100 students
and print the result using class student, and its member functions
getdata(); and result();

108
Friend function
• non members cannot access the private data of the class .

• Situations where we may require some data to be shared between two


class.

• C++ allows the function to be made friendly to both the classes.

• Friend function can access private members of both the classes

109
Friend function contd..….

class ABC
{
public:
friend void XYZ();

};

friend is a keyword
Such functions need not be a member of any of these functions.
Its defined as normal C++ function
(ie. It does not require a class name or scope resolution operator.)

110
Caracteristics Friend function

1. Its not in scope of any class to which it belongs

2. It cannot be called using objects


3. ie. Its called as normal C++ function.
4. It can be declared in private or public section of a class

5. Usually has objects as arguments.


6. It cannot access the member function directly. So to call the member
function we have to use objects and ‘ ‘ . ’ operator

111
Program to implement friend function
# include <conio.h>
class A
# include<iostream.h>
class A; { int val1;
class B public:
{ int val2; void get data()
public:
void get data() {
{ val1 = 40;
val2 = 20; }
}
void putdata() void putdata()
{ {
cout<<“value 2 = ”<<val2;
} cout<<“value 1 = ”<<val1;
}
friend exchange(A&, B&);
friend exchange(A&, B&);
};
};
112
void exchange (A &x, B &y)
{ int temp = x.val1;
x.val1 = y.val2;
y.val2 = temp;
}
void main()
{ A x;
B y;
x.getdata();
y.getdata();
x. putdata();
y.putdata();
exchange(x, y); // friend function needs no object
cout<<“after exchange”;
x. putdata();
y.putdata();
} 113
Class test: 4mks each

• What is class in C++? With a suitable explain Inside and


Outside function definitions with respect to class.

• What are constructors? Give characteristics of


constructor.

• Differentiate between object oriented programming


(OOP) and Procedure oriented Programming (POP).

• Explain
• Objects
• Classes

• WAP in C++ to implement circle class to find area and


circumference using functions void area() , void
circum(). 114
Operator overloading

The mechanism of giving some special


meaning to an operator is called as
operator overloading. To define an
additional task to an operator we
must specify, what it means in
relation to the class to which it is
applied. This is done with the help of
special function called operator
function.
115
Operator overloading
.
Operator function Syntax:
return type class name :: operator op(arg_list)
{
function body
}
Where op is the operator to be overloaded.
Here operator is a keyword. It provides a flexible option for the creation of
new definition for most C++ operators.
Type of operator function
operator function as member function

116
Program for operator overloading
class counter void main()
{ {
int count; counter c1,c2;
public:
cout<<“ c1 =
counter()
”<<c1.getcount();
{ count =0;
cout<<“ c2 =
}
int getcount()
”<<c2.getcount();
{
c1++;
return count; c2++;
}
void operator ++() cout<<“ c1 =
{ count ++; ”<<c1.getcount();
}
};
cout<<“ c2 =
”<<c2.getcount();
} 117
Program for operator overloading
class space void space :: operator -()
{ { x = -x;
int x,y,z; y = -y;
public: z = -z;
void gets(int a, int b, int c) }
{ x=a; void main()
y = b; { space s;
s.gets(10, -20, 30)
z= c;
} cout<<“ s = ”;
void operator -(); s.display();
void display() - s;
{ cout<<x<<y<<z; s.display();
}
}};

118
Rules of operator overloading
•Only existing operators can be overloaded.
New operator cannot be created.
•The overloaded operators must have at least
one operand that is of user-defined type.
•We cannot change the basic meanings of an
operator. That is to say, we cannot redefine the
plus (+) operator to subtract one value from
another.
•Overloaded operators follow the syntax rules of
the original operators. They cannot be
overridden.
119
Rules of operator overloading contd....
• There are some operators that cannot be overloaded. These are:
sizeof size of operator
. membership operator
. * Pointer to member operator
:: scope resolution operator
?: conditional operator
• we cannot use friend function to overload certain operators.
How ever member functions can be used to overload them.
= Assignment operator
() Function call operator
[] Subscripting operator
-> Class member access operator.

120
Rules of operator overloading contd....
• Unary operators, overloaded by means of a member
function, take no explicit arguments and return no
explicit value, but, those overloaded by means of
friend function take one reference argument (the
object of relevant class).

• Binary operators, overloaded by means of a member


function, take one explicit arguments and those
overloaded by means of friend function take two
explicit argument.

121
Rules of operator overloading contd....
• When using binary operators overloaded through a member function,
the left hand operand must be an object of relevant class.

• Binary arithmetic operator such as +,-, * and / must explicitly return a


value. They must not attempt to change their own arguments.

122
//PROGRAM FOR ADDITION OF TWO COMPLEX NUMBERS
class complex
{
public:
int x,y;
complex()
{ x=0;
y=0;
}
complex(int a,int b)
{ x=a;
y=b;
}

123
//PROGRAM FOR ADDITION OF TWO COMPLEX NUMBERS

void print(void)
{ cout<<x<<"+i"<<y<<endl;
}
complex operator+(complex);
};
complex complex::operator+(complex b1)
{ complex temp;
temp.x = x + b1.x;
temp.y = y + b1.y;
return temp;
}

124
void main()
{
clrscr();
complex A(11,22), B(33,44) , C;
C= A+B;
cout<<"Output"<<endl;
cout<<"\nThe 1st complex number is :";
A.print();
cout<<"\nThe 2nd complex number is :";
B.print();
cout<<"\nThe sum of the complex numbers is :";
C.print();
getch();
}

125
//PROGRAM FOR OVERLOADING +AND/OPERATOR
class ratio
{
public:
int num,den;
void getdata(void);
void print(void);
ratio operator+(ratio);
ratio operator/(ratio);
};

126
void ratio::getdata(void)
{
cout<<"numerator=";
cin>>num;
cout<<"denominator den=";
cin>>den;
}

void ratio::print(void)
{
if(den==1)
cout<<num<<endl;
else
cout<<num<<"/"<<den<<endl;
} 127
ratio ratio::operator+(ratio r4)
{ ratio temp;
temp.num=(num*r4.den)+(den*r4.num);
temp.den=den*r4.den;
return(temp);
}

ratio ratio::operator/(ratio r4)


{ ratio temp;
temp.num=(num*r4.den);
temp.den=(den*r4.num);
return(temp);
}

128
void main()
{
ratio r1,r2,r3,r5;
cout<<"Input:";
cout<<"\n first ratio:"<<endl;
r1.getdata();
cout<<"\n second ratio:"<<endl;
r2.getdata();
r3=r1+r2;
r5=r1/r2;
r1.print();
r2.print();
cout<<"\n addition =";
r3.print();
cout<<"\n Division =";
r5.print();
} 129
Type conversion
Theory:-
We know that constants and variables of different types
are mixed in an expression. C++ applies automatic type
conversions as per certain rules. Similarly an assignment
operator also causes automatic type conversions. The
type of data to the right of assignment operator is
automatically converted to the type of variable on the left.
eg: int i;
float p = 3.14;
p= i; // here i = 3
This will convert i to an integer before its value is assigned to p.
Fractional part is truncated.

130
Type conversion contd..…
Type conversions are automatic as long as the data
types involved are built in data types. But as the user
defined data types are built to suite our requirement,
the compiler does not support automatic type
conversion. So we need conversion routines for this.
There are three types of situations which may arise-

1. Conversion from basic to class (user defined


type).
2. Conversion from class to basic
3. Conversion from one class to another class

131
Initialise a constructor

1. Implicit call
number n1(20);

2. Explicit call
number n1 = 20;

132
Basic to class type
// int to class conversion

class time
void main()
{ {
int hrs; int duration = 85;
int mins; time t1 = duration;
}
public:
time ( int t)
{ hrs = t/60;
mins = t%60;
cout<<hrs<<“ : ”<<mins;
};
133
Basic to class type
After this conversion the hrs member of t1
will contain value 1, and min member will
contain value 25
ie. 1 hrs and 25 mins
The constructor used for this type of
conversion takes a single argument whose
type is to be converted.
In such conversions LHS is always object.
Therefore we can also accomplish this by
overloading = operator.
134
Class to Basic type
Two ways of class to basic conversions
Using casting operator function

Syntax:
operator typename()
{ …..
…. (function statements)
…….
}

135
Class Basic to type
C++ allows an overloaded casting operator function that can
be used to convert class type data to basic type data.
The general form of an overloaded casting operator function is
usually referred to as conversion function
operator type_name()
{
- function statements….
}
This function converts a class type data to type_name
e.g. operator double()
{
}
This will convert class_type to double or
operator int() will convert class_type to int.
136
Class Basic to type contd…

Casting operator function should satisfy the following conditions.

1. It must be a class member.


2. It must not specify return type.
3. It must not have any arguments.

Since it’s a member function, its invoked by an object and therefore the
values used for conversions inside the function belong to the object
that invoked it.

137
Class Basic to type
// overloaded operator function

class time
{
int hrs;
int mins;
public: void main()
{
time () time t1;
{ hrs = 1 ; int m = t1;
mins =25; }
}
operator int()
{ int min1 =hr * 60;
min1= min1 + min;
cout<<min1;
}};
138
Class to class to type
Two ways of class to class conversions
1. using operator function
Syntax:
operator typename()
{ …..
…. (function statements)
…….
}

2. Using constructor
139
There could be a situation where we would like to convert one class type
data to another class type data.

e.g. objx = objy


where x and y are objects of two different classes.
If objx is of class X and objy is of class Y, then Y is the source class and X is
the destination class.

140
Program for class to class conversion
class invent1;
{ int code;
int item;
float price;
public:
invent1(int a, int b , float c)
{ code = a;
item = b;
price = c;
}
void putdata()
{ cout<<“ code = ”<<code;
cout<<“item = ”<< item;
cout<<“price = ”<< price;
}

141
int getcode ()
{ return code;
}
int getitem ()
{ return item;
}
int getprice()
{ return price;
}};

142
class invent2
{
int code ;
float val;
public:
invent2()
{ code = 0;
val = 0;
}
invent2(invent1 p)
{ code = p.getcode();
val = p.getitem() * p.getprice();
}

143
void putdata()
{ cout<<“ code = ”<<code;
cout<<“ value = ”<< val;
}

};

void main()
{ invent1 s(100,5, 125.5);
invent2 d;
d = s; // convert invent1 to invent2
s.putdata();
d.putdata();
}

144
//A-6 PROGRAM FOR CONVERSION FROM POLAR CLASS TO RECTANGLE CLASS
AND RECTANGLE TO POLAR CLASS

class polar; /* "Polar" class declaration*/


class rectangle /* "rectangle" class defination*/
{
public:
float x,y;
void getdata()
{
cout<<"\n Enter x cord:-";
cin>>x;
cout<<"\n Enter y cord:-";
cin>>y;
}
void putdata()
{
cout<<"\n rectangular co-ordinates:=("<<x<<","<<y<<")";
}
operator polar();
145
};
class polar /* "Polar class defination*/
{
public:
float r,theta;
void getdata()
{
cout<<"\n Enter radius:-";
cin>>r;
cout<<"\n Enter theta:-";
cin>>theta;
}
void putdata()
{
cout<<"\n Polar co-ord("<<r<<","<<theta<<")";
}

operator rectangle();

};

146
polar :: operator rectangle()
{
rectangle rec;
rec.x=r*cos(theta*(3.14159/180));
rec.y=r*sin(theta*(3.14159/180));
return rec;
}

rectangle::operator polar()
{
polar p;
p.r = sqrt(x*x+y*y);
p.theta = atan(y/x)*(180/3.14159);
return p;
}

147
void main()
{
rectangle rec;
polar p;
cout<<"\nRectangular to polar";
rec.getdata();
p=rec;
cout<<"\n Output";
rec.putdata();
p.putdata();
cout<<"\nPolar to Rectangular\n";
p.getdata();
rec=p;
cout<<"\n Output";
p.putdata();
rec.putdata();
}
148
Inheritance

The mechanism of deriving new class (called


derived class) from the existing class (called base
class) is called as Inheritance. This is how C++
supports reusability. The old class is referred to
as base class and the new class is called the
derived class or subclass. Once the class has
been written and tested it can be adapted by
other programmers to suit their requirements.
This is basically done to create new classes by
using properties of the existing class. Functions
and variables of class that have been tested can
be used by objects of other classes. This is
known as Inheritance.

149
Inheritance contd……

Syntax:
class Derived_ class_ name : visibility mode Base_ class_ name
{
/* members of derived class */
};
e.g. class D : public B /* B is base class */
{
Members of derived class
};

150
Types of inheritances

• Single inheritance
• Multilevel inheritance
• Multiple inheritance
• Hierarchical inheritance
• Hybrid inheritance

151
Single inheritance

• A derived class with only one base class is called as single


inheritance.

Base class

Derived class

152
Program for single inheritance
class D : public B
class B {int c;
{int a; public:
void mul()
public: {c = b*geta();
int b; }
void display()
int geta() { cout<<“ a = ”<<geta();
{a =5; cout<<“ b = ”<<b;
cout<<“ c = ” <<c;
return a; }};

} void main()
void getb() {
D d;
{ b = 10; d.geta();
} d.getb();
d.mul();
}; d.display();
}
153
Multilevel inheritance

• Multilevel inheritance : The mechanism of deriving one class from an


already derived class is called as multilevel inheritance

Base class

Second base or
first derived class

Derived class

154
Program to implement multilevel inheritance

class student class test : public student


{protected : {
int rno; protected:
public: float sub1,sub2;
void getdata() public:
{ cout<<“enter roll no”; void getmarks()
cin>>rno; {cout<<“enter maths mks”;
} cin>>sub1>>sub2;
void putdata() }
{ cout<<“your roll no”<<rno; void putmarks()
}}; {
cout<<“ marks
”<<sub1<<sub2;
}};
155
class result : public test
void main()
{ {
float total; result R;
public: R.getdata();
R.getmarks();
void display()
{total = sub1+sub2; R.display();
putdata(); }
putmarks();
cout<<“ total = “<<total;
};

156
Multiple inheritance:
When a class is derived from several base classes, such type of inheritance is
called as multiple inheritance.

Base class1 Base class2 Base class3

Derived
class

157
Program to implement multiple inheritance
class M class P : public M, public
{ protected : N
int m; {
public: int mul;
void getm() public:
}; void display();
};
class N
{protected :
int n; void M :: getm()
public: {cout<<“enter m”;
void getn(); cin>>m;
}; }
158
Program to implement multiple inheritance

void N :: getn()
{ cout<<“enter n”; void main()
cin>>n;
} { P p1;
P1.getm();
void P :: display()
P1.getn();
{ mul = m*n;
cout<<“product of ”<<m<< P1.display();
“and”<< n<<“ is = ”<<mul;
}
}

159
Hierarchical inheritance
When more than one class is derived from one base class ,then such types
of inheritances are called as hierarchical inheritance

Base class

Derived Derived Derived


class1 class2 class3

160
Program to implement hierarchical inheritance 1
class student
{ void putdata()
protected : {
int rno, phy,chem; cout<<“your roll
no”<<rno;
public:
void getdata() cout<<“physics =
{ cout<<“enter roll “<<phy;
no”;
cin>>rno; cout<<“chemistry =
cout<<“enter phy ”<<chem;
and chem marks” }};
cin>>phy>>chem;
} 161
class maths : void putpcm()
public student { pcm =
{ protected: (phy+chem +m)/3;
int m; put();
float pcm; cout<<“ maths =
”<<m;
public: cout<<“ pcm =
void getpcm() ”<<pcm;
{ cout<<“enter };
maths mks”;
cin>>m;
}
162
class bio : public void putpcb ()
student { pcb = (phy+chem
{ protected: +b)/3;
put();
int b;
cout<<“ biology =
float pcb; ”<<b;
public: cout<<“ pcb =
void getpcb() ”<<pcb;
{ cout<<“enter bio }};
mks”;
cin>>b;
}
163
void main()
{
maths m1;
m1.get();
m1.getpcm();
m1.putpcm();

bio b1;
b1.get();
b1.getpcb();
b1.putpcb();
} 164
Hybrid inheritance

Inheritance which involves more than one type of inheritances is called


as hybrid inheritance.

Base class

Base class2 / Base class3 /


derived class1 derived class2

Derived class
165
Program for hybrid inheritance
class student
{ void putroll()
protected: {
int rollno; cout<<"the roll no
public: is- “ <<rollno
void getroll() <<"\n";
{ }};
cout<<"Enter the roll
no-\n ";
cin>>rollno;
}
166
class test:public student void puttest()
{protected:
float sub1,sub2; {
public: cout<<"\n marks in
void gettest() physics="<< sub1;
{
cout<<"Enter the marks sub21";
cin>>sub1; cout<<"\n The marks in
cout<<"Enter the mark sub2 "; sub2 ="<<sub2;
cin>>sub2;
}
};

167
class sports
{
protected:
float sp; void putsp()
public: {cout<<"\n Sports maks
void getsp() are="<<sp;
{
}};
cout<<"\n Enter the sports marks-
";
cin>>sp;
}

168
class result:public test, public sports
{ private:
float avg;
public:
void putresult()
{ avg=(p+m+sp)/3;
putroll();
puttest();
putsp();
cout<<"\n The result is"<<avg;
}};
169
void main()
{
result r;
r.getroll();
r.gettest();
r.getsp();
r.putresult();
}
170
Polymorphism

Polymorphism

Static binding Dynamic binding


Early binding Late binding

Compile time Run time


polymorphism polymorphism

Eg: function overloading eg: virtual function


operator overloading
171
Polymorphism
• It means ‘one name, multiple forms’. C++ supports two types of
Polymorphism.

• 1. Compile time polymorphism also known as Static binding. Function


overloading and Operator overloading are the examples of compile time
polymorphism.

• 2. Run time Polymorphism also known as Dynamic binding. It is


achieved using virtual function and using object pointer of type base
class.

172
Compile time Polymorphism
Polymorphism stands for many forms. In C++ it refers to identically named
member functions that have different behavior depending on the type of
objects it refers to.
Concept of polymorphism can be implemented using function overloading and
operator overloading.
The overloaded functions can be selected for invoking by matching the
arguments (in both type and number)
This information is known to the compiler at compile time and therefore
compiler can select the appropriate functions, such type of overloading is
known as compile time polymorphism, early binding or static binding.

173
Run time Polymorphism
Consider a situation where function name and prototype is same in
both base class and derived class.
e.g. class A
{ public:
void show(){}
};
class B : public A
{ public:
void show(){}
};
Here prototype of show() is same in base class and derived class ,
this is not function overloading, and this is allowed in C++. Here
static binding is not applicable and appropriate function can be
selected at run time and is called as run time polymorphism. For
that C++ supports the mechanism of virtual functions.
174
Run time Polymorphism
Here prototype of show() is same in base class and
derived class , this is not function overloading, and this is
allowed in C++. Here static binding is not applicable and
appropriate function can be selected at run time and is
called as run time polymorphism. For that C++ supports
the mechanism of virtual function.
At run time its known to the compiler as to which object
is under consideration and then the appropriate version
of the function is called.
As the function is linked with a particular class much later
after the compilation this process is called as late
binding. Because the selection of the appropriate
function is done dynamically at run time it is also called
as dynamic binding or run time polymorphism.
175
Pointer to objects.
An pointer can point to an object created by the class
e.g. item x; // item is a class and x is the object
item *ptr; // ptr is pointing to an obj of type item
we can also create object pointers to create objects at run time. We can
also use object pointers to access the public members of the objects
pointers can be initialized to an address of an object.
item *ptr = &x;

176
we can refer to member functions in two ways

1. . operator
2. → operator

ptr = &x;
x.putdata() ≈ ptr →putdata()
x.getdata() ≈ ptr →getdata()

177
we can create new objects using pointers and new operator
e.g. Item * ptr = new item ;

As also create an array


e.g. Item * ptr = new item[10] ;

Here memory space for an array of 10 objects of item is created


Then using pointers we can access members of objects.

178
Class test
• What is operator function? Explain any six rules of operator function.

• What is inheritance? Explain different types of inheritances.


• State characteristics of static data members.

• Write a short note on friend function and state characteristics of a


friend function.

• Write a program in C++ to find the no of occurrence of character ‘J’ in


the given string.

• Write a program in C++ to overload a binary + operator to add two


complex numbers.

179
Virtual function
• When we use same function name and prototype in both base and
derived classes, then the function in the base class is declared virtual.
When a function is made virtual, C++ determines at run time which
function is to be used. At run time it is known which object is under
consideration and then appropriate function is called.

180
Virtual function
• When we use same function name in both base and derived classes,
then the function in the base class is declared virtual. When a function is
made virtual, C++ determines at run time which function is to be used.
At run time it is known which object is under consideration and then
appropriate function is called.
• Though the prototype of the function is same in both derived class and
base class, the function is not overloaded. The appropriate member
functions can be selected at run time and this is called as run time
polymorphism. C++ supports the concept of run time polymorphism by
using virtual functions.

181
Virtual function contd..….
class base void main()
{ public: { Display base
void display () Show base
base B, *bptr; Display base
{ cout<<“display base”;
derived D; Show derived
}
virtual void show() cout<<“ptr points to base”;
{cout<<“show base”; bptr = &B;
}}; bptr-> display();
class derived : public base bptr-> show();
{ public: cout<<“ptr points to derived”;
void display ()
bptr = &D;
{ cout<<“display derived”;
bptr-> display();
}
void show() bptr-> show();
{cout<<“show derived”; getch();
}}; } 182
Virtual function contd….

NOTE :

➢ Base class pointer can point to base class objects and derived class objects.

➢ But derived class pointers cannot point to base class objects.

183
Virtual function contd….

NOTE ;

➢ When the function in base class and derived class have same prototype.

➢ base class function must be made virtual.

184
File handling in C++
• The data is stored in the devices(hard disk, floppy disk, CD etc.) using the
concept of files. A file is a collection of related data stored in the
particular area on the disk. Programs can be designed to perform read
and write operations on these files.

• We know the technique of handling the data communications


between the console unit and the program. (Using cin, cout). Various file
handling methods are available for storing and retrieving the data from
the files.

185
Working with files
INPUT STREAM

READING
DATA
DATA I/P

DISK FILE PROGRAM

DATA O/P

WRITING OUTPUT STREAM


DATA

186
A file is a collection of related data stored in a particular
area of the disk. Programs can be designed to perform
read and write operations on the disk.

A program typically involves either or both of the


following kinds of data communications.

1. Data transfer between the console unit and the program.


2. Data transfer between the program and disk files.

File operations use file streams as interface between


programs and files

The stream that supplies data to the program is known as


input stream and the one that receives data from the
program is known as output stream.
The input stream extracts or reads data from file.
Whereas output stream inserts or writes data to the file.
187
Classes for file stream operations
ios

istream streambuf ostream

iostream
FILE BUF

ifstream fstream ofstream

fstreambase
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 class and from
corresponding iostream class. These
classes are designed to manage the disk
files and we must include them in all the
program that use it.

189
Classes for file stream operations
……contd

• A stream is a general name given to the flow of data.

• Different streams are used to represent different data.

• Each stream is associated with a particular class, containing member


function definition for dealing with that particular flow of data

190
• fstream class:- provides simultaneous input and output operations. It
contains open () with default input mode and inherits all the functions
from istream and ostream through iostream class.

• ifstream class - provides input operations. Contains open () with default


input mode, inherits get (), getline(), read(), seekg(), close(), tellg()
functions through istream class.

• ofstream class - provides output operations. Contains open () with


default output mode. Inherits functions like put (), seekp(), tellp(),
write() functions through ostream class.

191
• fstream base: provides operations
common to file stream. Serves as base for
fstream , ifstream, and ofstream classes.
Contains open and close functons.

• filebuf : Its purpose is to set file buffers to


read and write modes. Contains close
functions.

192
Opening and closing a file.

While using a disk file, we need to decide the following


1. Suitable name for the file
2. data type and structure.
3. Purpose.
4. Opening method

193
Opening a file in Input mode –

A file can be opened in two ways


1. Using a constructor function
this method is useful when only one file is
in the stream.
2. Using the member function open().
this method is useful when we handle multiple
file is in the stream.

194
Steps involed in Opening a file in Input mode –

•Step 1. – we must create a file stream object .

e.g. file_stream_class stream_object;

• Step 2. – then link it to the file name using


open()
e.g. stream_object . open(“file name”);
195
Opening a file in Input mode –

Syntax:-
File_stream_class stream_object;
Stream_object . open(“file name”);

e.g.
ifstream fin1;
fin1.open(“Country.txt”);
/*This opens a file Country.txt in input mode i.e. for writing*/.
196
Opening a file in Output mode: –

File-stream-class stream object;

Stream object . open(“file name”);

e.g. ofstream fout1;


fout1.open(“Country.txt”);
/* This opens a file Country.txt in output mode i.e. for reading.*/

197
Closing file :-
syntax :-
Stream object .close();
e.g fout1.close();

198
Program for file handling in C++
#include <fstream.h>
void main()
{clrscr();
int i,n;
const int size = 20;
char countryarr[size];
char capitalarr[size];
ifstream fin1, fin2; //Creating a object of ifstream class for reading from the file

ofstream fout1, fout2; //Creating a object of ofstream class for writing to the file

fout1.open("Country.txt”); //Opening the file for write operations (output


mode)

fout2.open("Capital.txt");

199
cout << "Enter the number of countries";
cin >> n;
for (i=0; i < n; i++)
{
cout << "Enter the name of the country ";
cin >> countryarr;
fout1 << countryarr << endl;
cout << "Enter the name of the capital ";
cin >> capitalarr;
fout2 << capitalarr << endl;
}
fout1.close();
fout2.close();

200
fin1.open("Country.txt"); //Opening the file for read operations

fin2.open("Capital.txt");
while (fin1&&fin2)
{
if ((fin1.getline(countryarr , size)) ==NULL)
continue;
cout << "Capital of " << countryarr;
fin2.getline(capitalarr , size);
cout << " is " << capitalarr << endl;
}
fin1.close();
fin2.close();
getch();
}

201
File modes
fobj .open(“data.txt”, modes)
1. ios::app → append to the end of file
2. ios:: ate → go to the EOF
3. ios::binary → binary file
4. ios::in → open the file in read only
5. ios::nocreate →open fails if file does not exists.
6. ios::noreplace → open fails if the file already exists
7. ios::out → open the file for write only
8. ios::trunc → delete contents of fileif it exists.

Modes can be combined using bit wise or operator |


Eg: fout.open(“data.txt”, ios::app|ios::nocreate)

202
File pointers
• Each file has two associated pointers.

1. Input pointer or the get pointer


2. Output pointer or the put pointer

These are used to move through the file for reading or writing. As the
reading and writing takes place the pointer is automatically
incremented.

203
Default actions
OPEN THE FILE IN READ ONLY

H E L L O !

I/P POINTER

OPEN THE FILE IN APPEND

H E L L O !

O/P POINTER

OPEN THE FILE IN WRITE ONLY

O/P POINTER 204


functions for manipulation of file pointer.

All th.e above mentioned actions are default.


We can move the file pointer to desired positions
The file stream class supports the following following functions

205
The file stream class supports the following functions

1. seekg() : moves the I/P pointer to a specified location


2. seep() : moves the o/P pointer to a specified location
3. tellg() : gives the current position of get pointer
4. tellp() : gives the current position of put pointer

206
sequential I/P and O/P

• put() : writes a single character to the associated stream

• get() : reads a single character from the associated stream

We can use for loop along with get() and put() for reading
and writing a string.

207
write() and read()

unlike put() and get (), the read () and write (),
can handle data in binary format.

208
Copy constructor
A constructor can have a parameter of any type other than that of class to
which it belongs.
class A
{
A(A); // illegal in C++.
}
But it can accept a reference to its own class as parameter
class A
{
A(A&); // legal in C++.
}
Such constructors are called as copy constructor.

209
Copy constructor contd....

• Such constructors are called as copy constructor.

• The process of initialization through a copy constructor is known as


copy initiazation

• The copy constructor creates new class objects from an existing


objects of same class.

210
'this' pointer

• ‘this’ is a unique keyword, ‘this’ to represent an object that invoke a


member function

• ‘this’ is a pointer that points to the object for which this function was
called

• ‘this’ is unique pointer is automatically passed to a member function


when it is called

• class ABC
•{
int a;
}

211
'this' constructor contd…..

class ABC
{
int a;
};

a can be used directly in any member function


a = 123
this → a =123 same

Important application of this pointer is to return the object it points


return *this; will return the obj that invoked it

212
Binary file operations:

•In C++ by default the file stream operations are


performed in text mode, But we can store the
data in binary format. The functions read( ) and
write ( ), handle the data in binary format.
•An integer takes 2 bytes to store a 4digit
number, it takes 4bytes to store in character
form.
•Binary format is more accurate to store
numbers as there are no conversions while
saving and therefore saving the data I much
faster.

213
Virtual Base class

Grand parent class

Parent 1 Parent 2

Grand child class

214
In certain situations all the 3 types of inheritances namely multilevel,
multiple, hierarchical are invoked for deriving a new child class. The
child class has 2 direct base ie. parent 1 and parent 2 which themselves
have a common base class.
Here the grandchild class would have duplicate sets of members inherited
from grandparent via parent 1 and parent 2.
Because of this, ambiguity is created by duplication of inherited members
due to multiple path .This can be avoided by making common base class
virtual. This is done in inheritance definition .For a virtual base class only
1 copy of its members will be inherited regardless of number of path
between base class and derived class.

215
class a //Grandparent
{
}
class B : Virtual public A
{
}
class C:Virtual public A
{
}
class D:public A, public C
{
}
216
END

217

You might also like