XII C++ Jul 2023
XII C++ Jul 2023
1
C++
• C++ is Object Oriented programming
language.
2
Advantages of C++
•Incremented versions of C
• 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
6
Features of OOPS (contd…...)
8
Concepts of OOPs
• Objects
• Classes
• Inheritance
• Polymorphism
• Data abstraction and data encapsulation
• Dynamic binding
• Message passing
• Exception handling
9
XI review
• Keywords
• Identifiers
• Constant
• Operator
10
• Keywords : These are explicitly reserved and cannot
be used as names of program variables.
eg: int void etc
11
• Constants : Constants refers fixed values that
do not change during the execution of the
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…
16
Operators contd…
eg :
cout <<“enter the value of a ”;
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
19
new operator
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.
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
31
Steps include
• Function call
• Function definition
32
Function overloading
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
35
Why Inline function ……
• Lots of time is wasted when the function jumps from
calling function to the called function and back.
36
When inline request will be rejected
• 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
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.
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.
• Pointer is a variable
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
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
57
Reference feature of C++
• A function parameters
• As a return value
• A stand alone reference
58
1. Referance variable as parameter
Eg: if (x>y)
return &x;
else
return &y;
60
3. Referance variable as stand alone ref.
total/sum
100
2000
61
Pointers contd…...
• Call by value
• Call by reference
➢ 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
•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 :
public:
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
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. 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
3. Register A, B, C ,D, H, L
Static data members
class test
{
static void getdata();
}
Following characteristics
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
• 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
class integer
{
static int count;
}
91
Static member function
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)
delete.
97
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:-";
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 .
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
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
• Explain
• Objects
• Classes
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).
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.
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);
}
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-
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…
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.
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
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
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
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
Base class
Second base or
first derived class
Derived class
154
Program to implement multilevel inheritance
156
Multiple inheritance:
When a class is derived from several base classes, such type of inheritance is
called as multiple inheritance.
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
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
Base class
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
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 ;
178
Class test
• What is operator function? Explain any six rules of operator function.
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.
183
Virtual function contd….
NOTE ;
➢ When the function in base class and derived class have same prototype.
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.
185
Working with files
INPUT STREAM
READING
DATA
DATA I/P
DATA O/P
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.
iostream
FILE BUF
fstreambase
Classes for file stream operations
189
Classes for file stream operations
……contd
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.
191
• fstream base: provides operations
common to file stream. Serves as base for
fstream , ifstream, and ofstream classes.
Contains open and close functons.
192
Opening and closing a file.
193
Opening a file in Input mode –
194
Steps involed in 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: –
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
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.
202
File pointers
• Each file has two associated pointers.
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
H E L L O !
O/P POINTER
205
The file stream class supports the following functions
206
sequential I/P and O/P
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....
210
'this' pointer
• ‘this’ is a pointer that points to the object for which this function was
called
• class ABC
•{
int a;
}
211
'this' constructor contd…..
class ABC
{
int a;
};
212
Binary file operations:
213
Virtual Base class
Parent 1 Parent 2
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