KEMBAR78
CPP Lab Manualfinal | PDF | Integer (Computer Science) | C++
0% found this document useful (0 votes)
9 views68 pages

CPP Lab Manualfinal

The document provides a series of C++ programming examples illustrating various concepts such as variable scope, reference variables, ternary operators, control structures, and recursion. Each section includes a program, its output, and a brief description of the programming concept being demonstrated. The examples are aimed at teaching object-oriented programming principles using C++.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views68 pages

CPP Lab Manualfinal

The document provides a series of C++ programming examples illustrating various concepts such as variable scope, reference variables, ternary operators, control structures, and recursion. Each section includes a program, its output, and a brief description of the programming concept being demonstrated. The examples are aimed at teaching object-oriented programming principles using C++.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 68

OBJECT ORIENTED PROGRAMMING THROUGH C + +

1. AIM: C++ PROGRAM ILLUSTRATING VARIABLE SCOPE.


DESCRIPTION:
 C + + is an object oriented programming language.
 It was developed by Bjarne Stroustrup at AT & T Bell Laboratories in 1980’s.
 Stroustrup combined the best features of two languages ( C and Simula67) to create
a more powerful language that could support object oriented programming.
 C++ allows the declaration of variable anywhere in the scope i.e at time of its First
use
 We need to declare the variable before to the first use of it in our program. From the
declaration point the variables scope starts.

PROGRAM:
/* C++ PROGRAM TO ILLUSTRATE ABOUT A VARIABLE SCOPE */
#include<iostream.h>
#include<conio.h>
int a=10;
void main()
{
int x,y;
clrscr();
cout<<"\n enter values for x and y:\t";
cin>>x>>y;
int z=x+y;
cout<<"\n z value = "<<z;
int b=a+10;
cout<<"\n b value = "<<b;
getch();
}

OUTPUT:

enter values for x and y: 1 4

z value = 5

b value = 20

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


1
OBJECT ORIENTED PROGRAMMING THROUGH C + +
2. AIM: C++ PROGRAM TO SWAP TWO NUMBERS USING REFERENCE VARIABLES
DESCRIPTION:
C++ introduces a new kind of variable known as reference variable. A reference variable
provides an alias for a previously defined variable. If we make the variable sum a reference
to the variable total, then sum and total can be used interchangeably to represent that
variable. A reference variable is created as follows:
data-type & reference-name= variable-name
Example
float total = 100;
float & sum=total;
total is a float type variable that has already been declared; sum is alternative name
declared to represent variable total. Both the variables refer to the same data object in the
memory.
PROGRAM:
/* C++ PROGRAM TO SWAP TWO NUMBERS USING REFERENCE VARIABLES */
#include<iostream.h>
#include<conio.h>
void swap(int &,int &);
void main()
{
int a,b;
clrscr();
cout<<"\n enter values for a & b:";
cin>>a>>b;
cout<<"\n before swapping a = "<<a<<" b = " <<b;
swap(a,b);
cout<<"\n after swapping a = "<<a<<" b = "<<b;
getch();
}
void swap(int &a, int &b)
{
int c;
c=a;
a=b;
b=c;
}

OUTPUT:

enter values for a & b: 2 6


before swapping a = 2 b = 6
after swapping a = 6 b = 2
Prepared by G. VIJAYA KUMARI, Assoc.Prof.,
2
OBJECT ORIENTED PROGRAMMING THROUGH C + +
3. AIM: C++ PROGRAM TO FIND WHETHER THE GIVEN NUMBER IS EVEN OR ODD USING
TERNARY OPERATOR
DESCRIPTION:
C++ has a rich set of operators. All C operators are valid in C++ also.
The following syntax is used for a ternary operator
exp_1 ? exp _2 : exp_3
The system first evaluates the ‘exp_1’ values. If ‘exp_1’ value is true then it executes ‘exp_2’
otherwise it executes ‘exp_3’.

PROGRAM:
/* C++ PROGRAM TO FIND WHETHER THE GIVEN NUMBER IS EVEN OR ODD USING
TERNARY OPERATOR */
#include<iostream.h>
#include<conio.h>
void main()
{
int n;
clrscr();
cout<<"\n enter a number:\t";
cin>>n;
(n%2)==0?cout<<n<<" is even ":cout<<n<<" is odd ";
getch();
}

OUTPUT:

enter a number: 5
5 is odd

enter a number: 2
2 is even

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


3
OBJECT ORIENTED PROGRAMMING THROUGH C + +
4. AIM: C++ PROGRAM TO FIND THE ROOTS OF A QUADRATIC EQUATION USING SWITCH
STATEMENT
DESCRIPTION:
C + + supports 3 types of control structures. Those are
1. Sequence structure (straight line)
2. Selection structure (branching)
3. Loop structure (iteration or repetition)
Switch is an example for selection structure. Its syntax is..
switch(expression)
{
case1:{
action1;
}
case2:{
action2;
}
default:{
action3;
}
}
action5;
PROGRAM:
/* C++ PROGRAM TO FIND THE ROOTS OF A QUADRATIC EQUATION USING SWITCH
STATEMENT */
#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c,x;
clrscr();
cout<<"\n enter values for a,b,c:\t";
cin>>a>>b>>c;
int d=b*b-4*a*c;
if(d>0)
x=1;
else if(d==0)
x=2;
else

x=3;
Prepared by G. VIJAYA KUMARI, Assoc.Prof.,
4
OBJECT ORIENTED PROGRAMMING THROUGH C + +
switch(x)
{
case 1: float r1=(-b+sqrt(d))/(2*a);
float r2=(-b-sqrt(d))/(2*a);
cout<<"\n roots are real";
cout<<"\n r1 = "<<r1;
cout<<"\n r2 = "<<r2;
break;
case 2: r1=r2=(-b)/(2*a);
cout<<"\n roots are equal";
cout<<"\n r1 = "<<r1;
cout<<"\n r2 = "<<r2;
break;
case 3: d=sqrt(abs(d));
double x=double((-b)/(2*a));
double y=double(d/(2*a));
cout<<"\n roots are complex";
cout<<"\nr1 = "<<x<<"+"<<y<<"i";
cout<<"\nr2 = "<<x<<"-"<<y<<"i";
break;
default: cout<<"invalid option";
}
getch();
}
OUTPUT:
1. enter values for a,b,c: 1 4 1
roots are real
r1=-0.267949
r2 = -3.732051

2. enter values for a,b,c: 1 2 1


roots are equal
r1 = -1
r2 = -1

3. enter values for a,b,c: 1 3 8


roots are complex
r1 = -1+2i
r2 = -1-2i

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


5
OBJECT ORIENTED PROGRAMMING THROUGH C + +
5. AIM: C++ PROGRAM TO MULTIPLY TWO NUMBERS AFTER CHECKING THE
COMPATABILITY
DESCRIPTION:
To perform multiplication between any two numbers, we should verify that both the
numbers must be non zeros. If any one of them is zero the result is also zero. In order to get
a positive result we need to verify the multiplication compatibility among the two numbers.

PROGRAM:
/* C++ PROGRAM TO MULTIPLY TWO NUMBERS AFTER CHECKING THE
COMPATABILITY */
#include<iostream.h>
#include<conio.h>
void main()
{
int x,y;
clrscr();
L1: cout<<"\n enter two numbers:";
cin>>x>>y;
if((x!=0)&&(y!=0))
cout<<"\n multiplication of "<<x<<" and "<<y<<" is: "<<x*y;
else
{
cout<<"\n values must be non zero";
goto L1;
}
getch();
}

OUTPUT:

Enter two numbers: 2 0


Values must be non zero
Enter two numbers 2 6
Multiplications of 2 and 6 is: 12

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


6
OBJECT ORIENTED PROGRAMMING THROUGH C + +
6. AIM: C++ INTERACTIVE PROGRAM TO FIND ROOTS OF A QUADRATIC EQUATION
DESCRIPTION:
The do-while is an exit-controlled loop. Based on a condition, the control, the control is
transferred back to a particular point in the program.
The syntax is as follows:
do
{
action1;
} while(condition is true);
action2;
In order to implement an interactive program we used ‘do – while’ statement in our
program.

PROGRAM:
/* C++ INTERACTIVE PROGRAM TO FIND ROOTS OF A QUADRATIC EQUATION */
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<process.h>
void main()
{
int a,b,c,d;
char ch;
clrscr();
do
{
cout<<"\n************ MENU *********************";
cout<<"\n r->real roots \n e->equal roots \n c->complex roots
\n x->exit";
cout<<"\n enter your option:\t";
cin>>ch;
switch(ch)
{
case 'r': cout<<"\n enter a,b,c values:\t";
cin>>a>>b>>c;
d=b*b-4*a*c;
float r1,r2;
if((d>0)&&(a!=0))
{
r1=(-b+sqrt(d))/(2*a);

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


7
OBJECT ORIENTED PROGRAMMING THROUGH C + +
r2=(-b-sqrt(d))/(2*a);
cout.setf(ios::fixed,ios::floatfield);
cout<<"r1="<<r1;
cout<<"\n r2="<<r2;
}
else
cout<<"\n real roots are not possible for entered
values";
break;
case 'e' : cout<<"\n enter a,b,c values:\t";
cin>>a>>b>>c;
d=b*b-4*a*c;
if((d==0)&&(a!=0))
{
r1=r2=-b/(2*a);
cout.setf(ios::fixed,ios::floatfield);
cout<<"\n r1="<<r1;
cout<<"\n r2="<<r2;
}
else
cout<<"\n equal roots are not passible for the
entered values";
break;
case 'c' : cout<<"\n enter a,b,c values:\t";
cin>>a>>b>>c;
d=b*b-4*a*c;
double x,y;
if((d<0)&&(a!=0))
{
d=sqrt(abs(d));
x=-b/(2*a);
y=d/(2*a);
cout<<"\n d = "<<d;
cout.setf(ios::fixed, ios::floatfield);
cout<<"\n r1="<<x<<"+"<<y<<"i";
cout<<"\n r2="<<x<<"-"<<y<<"i";
}
else
cout<<"complex roots are not possible for the

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


8
OBJECT ORIENTED PROGRAMMING THROUGH C + +
entered values ";
break;
case 'x' : exit(0);
}
}while(ch!='x');
}

OUTPUT:
************************MENU********************
r -> real roots
e -> equal roots
c -> complex roots
x -> exit
enter your option: r
enter a,b,c values: 1 4 1
r1 = -0.267949
r2 = -3.732051

************************MENU********************
r -> real roots
e -> equal roots
c -> complex roots
x -> exit
enter your option: e
enter a,b,c values: 1 2 1
r1 = -1
r2 = -1

************************MENU********************
r -> real roots
e -> equal roots
c -> complex roots
x -> exit
enter your option: c
enter a,b,c values: 1 3 8
d=4
r1 = -1+2i
r2 = -1-2i

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


9
OBJECT ORIENTED PROGRAMMING THROUGH C + +
************************MENU********************
r -> real roots
e -> equal roots
c -> complex roots
x -> exit
enter your option: x

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


10
OBJECT ORIENTED PROGRAMMING THROUGH C + +
7. AIM: C++ PROGRAM TO SORT INTEGERS
DESCRIPTION: Sorting means arranging the given elements either in increasing or in
decreasing order.
The following program is used to sort the given numbers in ascending order.
PROGRAM:
/* C++ PROGRAM TO SORT INTEGERS */
#include<iostream.h>
#include<conio.h>
void main()
{
int a[10],i,j,n,temp;
clrscr();
cout<<"\n enter n value:\t";
cin>>n;
cout<<"\n enter "<<n<<" elements:\n" ;
for(i=0;i<n;i++)
cin>>a[i];
for(i=0;i<n;i++)
{
for(j=i;j<(n-1);j++)
{
if(a[i]>a[j+1])
{
temp=a[i];
a[i]=a[j+1];
a[j+1]=temp;
}
}
}
cout<<"\n elements after sorting are...\n";
for(i=0;i<n;i++)
{
cout<<a[i];
cout<<"\t";
}
getch();
}

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


11
OBJECT ORIENTED PROGRAMMING THROUGH C + +
OUTPUT:

enter n value: 5
enter 5 elements : 6 5 1 9 2
elements after sorting are…
1 2 5 6 9

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


12
OBJECT ORIENTED PROGRAMMING THROUGH C + +
8. AIM: C++ PROGRAM TO FIND THE FACTORIAL OF A NUMBER USING RECURSION
DESCRIPTION:
C + + language supports recursive feature, that is a function calls itself repetitively. In
recursion a function calls itself and the control goes to the same function and it executes
repeatedly until some condition is satisfied. Recursion is turning out to be increasingly
important in non numeric applications and symbolic manipulations. To stop the recursive
function, it is necessary to base the recursion on test condition, and proper terminating
statement such as exit() or return() must be written using if() statement.

PROGRAM:
/* C++ PROGRAM TO FIND THE FACTORIAL OF A NUMBER USING RECURSION */
#include<iostream.h>
#include<conio.h>
int fact(int);
void main()
{
int n;
clrscr();
cout<<"\n enter a number:\t";
cin>>n;
cout<<"\n factorial of "<<n<<" is "<<fact(n);
getch();
}
int fact(int n)
{
if(n==1)
return(n);
else
return(n*fact(n-1));
}

OUTPUT:

enter a number: 5
factorial of 5 is 120

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


13
OBJECT ORIENTED PROGRAMMING THROUGH C + +
9. AIM: C++ PROGRAM TO ILLUSTRATE ABOUT PASS BY VALUE, PASS BY ADDRESS & PASS BY
REFERENCE
DESCRIPTION:
The main objective of passing argument to function is message passing. The message
passing is also known as communication between two functions that is between caller and
called functions. There are 3 methods by which we can pass values to the function. Those
are
1. Call by value: in this type, values of actual arguments are passed to the formal
arguments and operation is done on the formal arguments. Any change in the formal
arguments does not effect to the actual arguments because formal arguments are
photocopy of actual arguments. Changes made in formal arguments are local to the
block of called function only.
2. Call by address: in this type, instead of passing values, addresses of actual
parameters are passed to the functions by using pointers. Functions operate on
addresses rather than values. Here the formal arguments are pointers to the actual
arguments. Because of this, when the values of formal arguments are changed, the
values of actual parameters also change. Hence changes made in the argument ar
permanent.
3. Call by reference: C + + reference types, declared with ‘&’ operator, are nearly
identical but not exactly the same as pointer types. They declare aliases for objects
variables and allow the programmer to pass arguments by reference to functions.
PROGRAM:
/* C++ PROGRAM TO ILLUSTRATE ABOUT PASS BY VALUE, PASS BY ADDRESS &
PASS BY REFERENCE */
#include<iostream.h>
#include<conio.h>
void swap(int,int);
void ref(int &,int &);
void addrs(int *,int *);
void main()
{
int a,b;
clrscr();
cout<<"\n enter a, b values:\t";
cin>>a>>b;
swap(a,b); // call by value method
cout<<" \n after swap a= "<<a<<" b = "<<b;
ref(a,b); // call by reference method
cout<<"\n after ref a = "<<a<<" b = "<<b;
addrs(&a,&b); // call by address method
cout<<"\n after addrs a = "<<a<<" b = "<<b;
getch();
}

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


14
OBJECT ORIENTED PROGRAMMING THROUGH C + +

void swap(int a, int b)


{
int c;
c = a;
a = b;
b = c;
}
void ref(int &a, int &b)
{
int c;
c = a;
a = b;
b = c;
}
void addrs(int *a,int *b)
{
int c;
c = *a;
*a = *b;
*b = c;
}

OUTPUT:
enter a , b values: 2 8

after swap a = 2 b = 8

after ref a = 8 b = 2

after addrs a = 2 b = 8

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


15
OBJECT ORIENTED PROGRAMMING THROUGH C + +
10. AIM: C++ PROGRAM TO ILLUSTRATE ABOUT FUNCTION OVERLOADING
DESCRIPTION:
Overloading refers to the use of the same thing for different purposes. C++ also permits
overloading of functions. This means that we can use the same function name to create
functions that perform a variety of different tasks. This is known as function polymorphism
in OOP.
Using the concept of function overloading, We can design a family of functions with one
function name but with different arguments lists. The function would perform different
operations depending on the arguments list in the function call. The correct function to be
invoked is determined by checking the number and type of arguments but not on the
function type.
For example, an overloaded add() function handles different type of data as shown below:
// Declarations//
int add(inta,int b);
int add(inta,int b, int c);
double add(double x, double y);
double add(int p, double q);
double add(double p, int q);

//Function calls//
cout<<add(5, 10);
cout<<add(15, 10.0);
cout<<add(12.5, 7.5);
cout<<add(5, 10,15);
cout<<add(0.75, 5);

PROGRAM:
/* C++ PROGRAM TO ILLUSTRATE ABOUT FUNCTION OVERLOADING */
#include<iostream.h>
#include<conio.h>
int volume(int);
float volume(float,int);
double volume(double,int,int);
void main()
{
int s;
clrscr();
cout<<" \n enter s value:\t";
cin>>s;
cout<<"\n volume of cube = "<<volume(s);

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


16
OBJECT ORIENTED PROGRAMMING THROUGH C + +
float r;
int h;
cout<<"\n enter r and h values:\t";
cin>>r;
cin>>h;
cout<<"\n volume of cylinder = "<<volume(r,h);
double l;
int b,ht;
cout<<"\n enter l , b, ht values:\t";
cin>>l;
cin>>b>>ht;
cout<<"\n volume of a rectangle box = "<<volume(l,b,ht);
getch();
}
int volume(int s)
{
return(s*s*s);
}
float volume(float r, int h)
{
return(3.145*r*r*h);
}
double volume(double l, int b, int h)
{
return(l*b*h);
}

OUTPUT:
enter s value: 3
volume of cube = 27

enter r and h values: 2 4


volume of cylinder = 50.32

enter l, b, ht values: 1 2 6
volume of a rectangle box = 12

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


17
OBJECT ORIENTED PROGRAMMING THROUGH C + +
11. AIM: C++ PROGRAM TO SWAP TWO INTEGERS, FLOATING NUMBERS & CHARACTERS
WITHOUT USING FUNCTION OVERLOADING
DESCRIPTION:
Overloading refers to the use of the same thing for different purposes. C++ also permits
overloading of functions. This means that we can use the same function name to create
functions that perform a variety of different tasks. This is known as function polymorphism
in OOP.
In C, Polymorphism is not possible. The following program illustrates about swapping
numbers without using polymorphism.

PROGRAM:
/* C++ PROGRAM TO SWAP TWO INTEGERS, FLOATING NUMBERS & CHARACTERS
WITHOUT USING FUNCTION OVERLOADING */
#include<iostream.h>
#include<conio.h>
#include<process.h>
void main()
{
int op;
clrscr();
do
{
cout<<"\n-----------MENU--------------";
cout<<"\n 1->integers swapping\n2->floating swapping \n
3->character swapping\n4->exit";
cout<<"\n enter your option:\t";
cin>>op;
switch(op)
{
case 1: int a,b,c;
cout<<"\n enter two integer values:\t";
cin>>a>>b;
cout<<"\n before swapping a = "<<a<<" b = "<<b;
c=a;
a=b;
b=c;
cout<<"\n after swapping a= "<<a<<" b = "<<b;
break;
case 2: float x,y,z;
cout<<"\n enter two floating values:\t";
cin>>x>>y;

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


18
OBJECT ORIENTED PROGRAMMING THROUGH C + +
cout<<"\n before swapping x = "<<x<<" y = "<<y;
z=x;
x=y;
y=z;
cout<<"\n after swapping x= "<<x<< " y = "<<y;
break;
case 3: char c1,c2,c3;
cout<<"\n enter two characters:\t";
cin>>c1>>c2;
cout<<"\n before swapping c1 = "<<c1<< " c2 = "<<c2;
c3=c1;
c1=c2;
c2=c3;
cout<<"\n after swapping c1 = "<<c1<<" c2 = "<<c2;
break;
case 4: exit(0);
}
} while(op!=4);
getch();
}

OUTPUT:
---------------MENU-----------------------
1-> integers swapping
2-> floating swapping
3-> character swapping
4->exit
enter your option: 1
enter two integer values:1 5
before swapping a = 1 b= 5
after swapping a = 5 b = 1
---------------MENU-----------------------
1-> integers swapping
2-> floating swapping
3-> character swapping
4->exit

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


19
OBJECT ORIENTED PROGRAMMING THROUGH C + +
enter your option: 2
enter two floating values: 1.3 4.8
before swapping x = 1.3 y = 4.8
after swapping x = 4.8 y = 1.3
---------------MENU-----------------------
1-> integers swapping
2-> floating swapping
3-> character swapping
4->exit
enter your option: 3
enter two characters: v k
before swapping c1 = v c2 = k
after swapping c1 = k c2 = v
---------------MENU-----------------------
1-> integers swapping
2-> floating swapping
3-> character swapping
4->exit
enter your option: 4

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


20
OBJECT ORIENTED PROGRAMMING THROUGH C + +
/* C++ PROGRAM TO SWAP TWO INTEGERS, FLOATING NUMBERS & CHARACTERS USING
FUNCTION OVERLOADING */
#include<iostream.h>
#include<conio.h>
void swap( int,int);
void swap(float,float);
void swap(char,char);
void main()
{
clrscr();
int a,b;
cout<<"\n enter two integers:\t";
cin>>a>>b;
swap(a,b);
float x,y;
cout<<"\n enter two floating numbers:\t";
cin>>x>>y;
swap(x,y);
char c1,c2;
cout<<"\n enter two characters:\t";
cin>>c1>>c2;
swap(c1,c2);
getch();
}
void swap(int a,int b)
{
int c;
cout<<"\n before swapping a = "<<a<<" b = "<<b;
c=a;
a=b;
b=c;
cout<<"\n after swapping a = "<<a<<" b = "<<b;
}
void swap(float a, float b)
{
float c;
cout<<"\n before swapping a = "<<a<<" b = "<<b;
c=a;
a=b;
b=c;

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


21
OBJECT ORIENTED PROGRAMMING THROUGH C + +
cout<<"\n after swapping a = "<<a<<" b = "<<b;
}

void swap(char a,char b)


{
char c;
cout<<"\n before swapping a = "<<a<<" b = "<<b;
c=a;
a=b;
b=c;
cout<<"\n after swapping a = "<<a<<" b = "<<b;
}

OUTPUT:
enter two integers: 1 3
before swapping a = 1 b=3
after swapping a = 3 b=1

enter two floating numbers: 1.2 4.5


before swapping a = 1.2 b = 4.5
after swapping a = 4.5 b = 1.2

enter two characters: v k


before swapping a = v b=k
after swapping a = k b=v

12. AIM: C++ PROGRAM TO ILLUSTRATE ABOUT INLINE FUNCTIONS


Prepared by G. VIJAYA KUMARI, Assoc.Prof.,
22
OBJECT ORIENTED PROGRAMMING THROUGH C + +
DESCRIPTION:
One of the objectives of using functions in a program is to save some memory space, which
becomes appreciable when a function is likely to be called many times. However, every time
a function is called, it takes a lot of extra time in executing a series of instructions for tasks
such as jumping to the calling function. When a function is small, a substantial percentage of
execution time may be spent in such overheads.
One solution to this problem is to use macro definitions, popularly known as macros.
C++ has different solutions to this problem. To eliminate the cost of calls to small functions
expanded in line when it is invoked. That is, the compiler replaces the functions call with the
corresponding function code (something similar to macros expansion). The inline function
are defined as follows:

inline function-header
{
function body
}
Example:
inline double cube(double a)
{
return(a*a*a);
}

PROGRAM:

/* C++ PROGRAM TO ILLUSTRATE ABOUT INLINE FUNCTIONS */


#include<iostream.h>
#include<conio.h>
inline float mul(float x,float y)
{
return (x*y);
}
inline float div(float x, float y)
{
return(x/y);
}
void main()
{
float a=12.34;
float b = 9.82;
clrscr();
cout<<"\n after multiplication result = "<<mul(a,b);

cout<<"\n after division result = "<<div(a,b);


Prepared by G. VIJAYA KUMARI, Assoc.Prof.,
23
OBJECT ORIENTED PROGRAMMING THROUGH C + +
getch();
}

OUTPUT:

After multiplication result = 121.178795


After division result = 1.256619

13. AIM: C + + PROGRAM TO IMPLEMENT FRIEND FUNCTION


Prepared by G. VIJAYA KUMARI, Assoc.Prof.,
24
OBJECT ORIENTED PROGRAMMING THROUGH C + +
DESCRIPTION:
The central idea of encapsulation and data hiding concept is that any non member function
has no access permission to the private data of the class. The private members of the class
are accessed only from member functions of that class.
C + + allows a mechanism, in which a non member function has access permission to the
private members of the class. This can be done by declaring non member function friend to
the class whose private is to be accessed. The ‘friend’ is a keyword. The keyword ‘friend’
must be precede the function declaration. The function can be defined at any place in the
program like normal function
Example: friend void show( arg1,arg2…);
Properties of a friend function:
1. There is no scope restriction for the friend function. Hence, they can be called
directly without using object.
2. Friend cannot access the member directly. It uses the dot operator and object to
access the private & public data of the class.
3. Friendship is not shared.
4. Use of friend function is rare, since it violates the rules of encapsulation and data
hiding.

PROGRAM:
/* CPP PROGRAM TO IMPLEMENT FRIEND FUNCTION*/
#include<iostream.h>
#include<conio.h>
class base
{
int val1,val2;
public:void get()
{
cout<<"enter two values:";
cin>>val1;
cin>>val2;
}
friend float mean(base ob);
};
float mean(base ob)
{
return float(ob.val+ob.val2)/2;
}
void main()
{
base obj;

obj.get();

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


25
OBJECT ORIENTED PROGRAMMING THROUGH C + +
cout<<"mean value is:"<<mean(obj);
getch();
}
Output:
Enter two values: 5 6
Mean value:5.5

14. AIM: C + + PROGRAM FOR EXCEPTION HANDLING


DESCRIPTION:
Prepared by G. VIJAYA KUMARI, Assoc.Prof.,
26
OBJECT ORIENTED PROGRAMMING THROUGH C + +
Developing an error free program is the only objective and intention of the programmer.
Programmer should take care to prevent errors. Errors can be trapped using exception
handling features.
An exception is an abnormal termination of the program, which is executed in a program at
run time or it may be called at runtime when an error occur. The exception contains warning
messages such as invalid argument, insufficient memory, and division by zero.
Exception handling mechanism in C + + uses 3 keywords.
1. Try : it contains series of statements which may raise an exception in our program
2. Throw: it is used to send the exception found in the program.
3. Catch: it contains series of statements to handle the exception.
Exception handling technique passes the control of a program from a location of exception
in a program to an exception handling routine linked with the try block. An exception
handler routine can only be called by the throw statement.
PROGRAM:
/* CPP PROGRAM FOR EXCEPTION HANDLING*/
#include<iostream.h>
#include<conio.h>
void main()
{
int x,y;
clrscr();
cout<<"\n enter x and y values";
cin>>x>>y;
try
{
if(y!=0)
{
cout<<"x/y="<<x/y;
}
else
throw(y);
}
catch(int z)
{
cout<<"\n value must be non-zero";
}
getch();
}

Output:

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


27
OBJECT ORIENTED PROGRAMMING THROUGH C + +
Enter x and y values:6 3
x/y=2
Enter x and y values: 6 0
The value must be non-zero

15. AIM: C + + PROGRAM ILLUSTRATING FUNCTION TEMPLATE

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


28
OBJECT ORIENTED PROGRAMMING THROUGH C + +
DESCRIPTION:
Template is a technique that allows a single function or class to work with different data
types. Using a template, we can create a single function that can process any type of data;
that is, the formal arguments of a template function are of template (generic) type. They
can accept data of any type, such as int, float, and long.
Syntax: template<class T>
Return data type function_name( parameters of template type)
{
Statement1
Statement2
Statement 3
};

PROGRAM:
/* CPP PROGRAM ILLUSTRATING FUNCTION TEMPLATE*/
#include<iostream.h>
#include<conio.h>
template<class T>
void show(T x)
{
cout<<"\n x="<<x;
}
void main()
{
clrscr();
char c='A';
int i=40;
double d=65.535;
show(c);
show(i);
show(d);
getch();
}

OUTPUT: X=A
X=40
X=65.535

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


29
OBJECT ORIENTED PROGRAMMING THROUGH C + +
16. AIM: C++ PROGRAM FOR OVERLOADING INCREMENT &DECREMENT
OPERATORS,BINARY + AND << OPERATORS
DESCRIPTION:
Operator overloading is one of the many exciting features of C++ language. It is an
important technique that has enhanced the power of extensibility of C++. We have stated
more than once that C++ tries to make the user-defined data types behave in much the
same way as the built-in types. For instance C++ permits us to add two variables of user-
defined types with the same syntax that is applied to the basic types. The mechanism of
giving such special meanings to an operator is known as operator overloading.
Operator overloading provides a flexible option for the creation of new definitions for most
of the C++ operators. We can overload (give additional meaning to) all the C++ operators
except the following.
 Class member access operators (., . *).
 Scope resolution operator (::).
 Size operator (size of).
 Conditional operator (?:).

PROGRAM:
/*C++ PROGRAM FOR OVERLOADING INCREMENT &DECREMENT OPERATORS
*/
#include<iostream.h>
#include<conio.h>
class number
{
float x;
public:number(float k)
{
x=k;
}
void operator++(int)
{
x++;
}
void operator--()
{
--x;
}

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


30
OBJECT ORIENTED PROGRAMMING THROUGH C + +
void show()
{
cout<<"\n x="<<x;
}
};
void main()
{
clrscr();
number N(2.3);
cout<<"\n before incrementing:";
N.show();
cout<<"\n after decrementation";
N++;
N.show();
cout<<"\n after decrementation:";
--N;
N.show();
getch();
}
OUTPUT: before incrementing:
X=2.3
After incrementing
X=3.3
After decrementation
X=2.3

/* PROGRAM TO OVERLOAD INSERTION(<<)OPERATORS USING FRIEND


FUNCTION*/
PROGRAM:
#include<iostream.h>
#include<conio.h>
class string
{
char *s;

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


31
OBJECT ORIENTED PROGRAMMING THROUGH C + +
public:string(char *k)
{
s=k;
}
friend ostream &operator<<(ostream &put,string &k)
{
put<<k.s;
return put;
}
}
int main()
{
clrscr();
string s("INDIA");
cout<<s;
return 0;
}

OUTPUT: INDIA

/*CPP PROGRAM FOR OVERLOADING BINARY+ OPERATOR*/


PROGRAM:
#include<iostream.h>
#include<conio.h>
class num
{
private:int a,b,c,d;
public:void input(void);
void show(void);
num operator+(num);
};
void num::input()
{

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


32
OBJECT ORIENTED PROGRAMMING THROUGH C + +
cout<<"\n enter values for a,b,c,d";
cin>>a>>b>>c>>d;
}
void num::show()
{
cout<<"A="<<a<<"B="<<b<<"C="<<c<<"D="<<d<<endl;
}
num num::operator+(num k)
{
num temp;
temp.a=a+k.a;
temp.b=b+k.b;
temp.c=c+k.c;
temp.d=d+k.d;
return temp;
}
main()
{
clrscr();
num x,y,z;
cout<<"\n object x";
x.input();
cout<<"\n object y";
y.input();
z=x+y;
cout<<"\n x:";
x.show();
cout<<"\n y:";
y.show();
cout<<"z";
z.show();
getch();
return 0;
}

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


33
OBJECT ORIENTED PROGRAMMING THROUGH C + +
OUTPUT:
Object x
Enter values for a,b,c,d:3 6 5 8
Object y
Enter values for a,b,c,d: 1 2 4 8
X: A=3 B=6 C=5 D=8
Y: A=1 B=2 C=4 D=8
Z:A=4 B=8 C=9 D=16

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


34
OBJECT ORIENTED PROGRAMMING THROUGH C + +
17.AIM: C + + PROGRAM TO IMPLEMENT VIRTUAL FUNCTION
DESCRIPTION:
One of the key features offered by C++ is polymorphism. The information pertaining to
various overloaded member functions and arguments is known to the compiler. The
compiler selects the appropriate function and collects the arguments at compiler time this is
called early binding or static binding.
Through C++ is an object oriented programming language. It is very much inspired by
procedural language. When a function call is encountered by the compiler during execution
binding takes place. This binding refers in the process that is to be used for converting
functions and variables into machine language address. We have two types in binding.
1. Static binding: Even though similar function names are used at many places,
references and their positions are indicated explicitly by the compiler. Their
ambiguities are fixed at compile time.
2. Dynamic binding: In a case of few programs, it is impossible to know which function
is to be called until run time. This is called dynamic binding. Dynamic binding of
member functions in C++ can be done using the virtual keyword. The member
function followed by the virtual key word is called virtual function.

PROGRAM:
/* CPP PROGRAM TO IMPLEMENT VIRTUAL FUNCTION*/
#include<iostream.h>
#include<conio.h>
class base
{
public:
virtual void show()
{
cout<<"\n base class show:";
}
void display()
{
cout<<"\n base class display:";
}
};
class drive: public base
{
public:
void display()
{
cout<<"\n derived class display:";
}
void show()

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


35
OBJECT ORIENTED PROGRAMMING THROUGH C + +
{
cout<<"\n derived class show";
}
};
void main()
{
clrscr();
base obj1;
base *p;
cout<<"\n\t p points to base:\n";
p=&obj1;
p->display();
p->show();
cout<<"\n\n\t p points to drive:\n";
drive obj2;
p=&obj2;
p->display();
p->show();
getch();
}
Output:
P points to base:
base class display
base class show
P points to drive:
base class display
derived class show

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


36
OBJECT ORIENTED PROGRAMMING THROUGH C + +
18. AIM: C + + PROGRAM TO PERFORM DIFFERENT OPERATIONS ON TWO COMPLEX
NUMBERS
DESCRIPTION:
In order to implement an interactive program we used ‘do – while’ statement in our
program. The following program implements different operations on two complex numbers
using overloading of +, -, *, / operators.
And also it uses ‘class’ to represent the complex numbers.
PROGRAM:
/*CPP PROGRAM TO PERFORM DIFFERENT OPERATIONS ON TWO COMPLEX
NUMBERS*/
#include<iostream.h>
#include<conio.h>
class complex
{
int i,r;
public:
void read()
{
cout<<"\n enter real port:";
cin>>r;
cout<<"enter imaginary part:";
cin>>i;
}
void display()
{
cout<<"\n="<<r<<"+"<<i<<"i";
}
complex operator+(complex a2)
{
complex a;
a.r=r+a2.r;
a.i=i+a2.i;
return a;
}
complex operator-(complex a2)
{
complex a;
a.r=r-a2.r;
a.i=i-a2.i;
return a;
}

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


37
OBJECT ORIENTED PROGRAMMING THROUGH C + +

complex operator*(complex a2)


{
complex a;
a.r=(r*a2.r)-(i*a2.i);
a.i=(r*a2.i)+(i*a2.r);
return a;
}
complex operator/(complex a2)
{
complex a;
a.r=((r*a2.r)+(i*a2.i))/((a2.r*a2.r)+(a2.i*a2.i));
a.i=((i*a2.r)-(r*a2.i))/((a2.r*a2.r)+(a2.i*a2.i));
return a;
}

};
void main()
{
int ch;
clrscr();
complex a,b,c;
do
{
cout<<"\n 1.addition 2.subtraction"l;
cout<<"3.multiplication 4.division 5.exit\n";
cout<<"\n enter the choice:";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\n enter the first complex number:";
a.read();
a.display();
cout<<"\n enter the second complex number:";
b.read();
b.display();
c=a+b;
c.display();
break;

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


38
OBJECT ORIENTED PROGRAMMING THROUGH C + +

case 2:
cout<<"\n enter the first complex number:";
a.read();
a.display();
cout<<"\n enter the second complex number:";
b.read();
b.display();
c=b-a;
c.display();
break;
case 3:
cout<<"\n enter the first complex number:";
a.read();
a.display();
cout<<"\n enter the second complex number:";
b.read();
b.display();
c=a*b;
c.display();
break;
case 4:
cout<<"\n enter the first complex number:";
a.read();
a.display();
cout<<"\n enter the second complex number:";
b.read();
b.display();
c=a/b;
c.display();
break;
}
} while(ch!=5);
getch();
}

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


39
OBJECT ORIENTED PROGRAMMING THROUGH C + +

OUTPUT:
1.addition 2.subtraction
3.multiplication 4.division 5.exit
Enter the choice:1
Enter the first complex number:
Enter real part:2
Enter imaginary part:3
=2+3i
Enter the second complex number:
Enter real part:5
Enter imaginary part:2
=5+2i
=11+21i
1.addition 2.subtraction
3.multiplication 4.division 5.exit
Enter the choice:5

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


40
OBJECT ORIENTED PROGRAMMING THROUGH C + +

19. AIM: CPP PROGRAM TO IMPLEMENT STRING HANDLING FUNCTIONS WITH USER
DEFINED PROCESSING FUNCTION
DESCRIPTION:
Character array is known as string. Different operations are performed on a string by using
predefined functions available in “string.h” header file.
The following program illustrates finding length of a string, copying one string to another,
concatenating two strings, and comparing two strings without using any predefined
functions in “string.h” header file.

PROGRAM:
/* CPP PROGRAM TO IMPLEMENT STRING HANDLING FUNCTIONS WITH USER
DEFINED PROCESSING FUNCTION*/
#include<iostream.h>
#include<conio.h>
#include<string.h>
int my_strlen(char *str);
void my_strcpy(char *s2,char *s1);
void my_strcat(char *s2,char *s1);
void my_strcmp(char *s1,char *s2);
void main()
{
char temp[100],*s1,*s2,*s3;
clrscr();
cout<<"enter string1:";
cin>>temp;
s1=new char[strlen(temp)+1];
my_strcpy(s1,temp);
cout<<"enter string2:";
cin>>temp;
s2=new char[strlen(temp)+1];
my_strcpy(s2,temp);
cout<<"length of string1:"<<my_strlen(s1)<<endl;
s3=new char[strlen(s1)+my_strlen(s2)+1];
my_strcpy(s3,s1);
my_strcpy(s3,s2);
cout<<"strings on concatenation:"<<s3<<endl;
cout<<"strings comparison using:......"<<endl;
Prepared by G. VIJAYA KUMARI, Assoc.Prof.,
41
OBJECT ORIENTED PROGRAMMING THROUGH C + +

cout<<"library function:"<<strcmp(s1,s2)<<endl;
cout<<"user function:"<<my_strcmp(s1,s2)<<endl;
delete s1;
delete s2;
delete s3;
getch();
}
int my_strlen(char *str)
{
char *ptr=str;
while(*ptr!='\0')
++ptr;
return ptr-str;
}
void my_strcpy(char *s2,char *s1)
{
while(*s1!='\0')
*s2++=*s1++;
*s2='\0';
}
void my_strcat(char *s2,char *s1)
{
while(*s2!='\0')
s2++;
while(*s1!='\0')
*s2++=*s1++;
*s2='\0';
}

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


42
OBJECT ORIENTED PROGRAMMING THROUGH C + +

void my_strcmp(char *s1,char *s2)


{
while(*s1==*s2&&*s1!=NULL||*s2!=NULL)
{
s1++;
s2++;
}
return *s1-*s2;
}

OUTPUT:
Enter string1:object
Enter string2:oriented
Length of string1:6
Strings on concatenation:
Objectoriented
Strings comparison using….
Library function:-16
User function:-16

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


43
OBJECT ORIENTED PROGRAMMING THROUGH C + +
20. AIM: C + + PROGRAMS TO IMPLEMENT DEFAULT AND PARAMETERIZED
CONSTRUCTOR
DESCRIPTION:
 Constructors have the same name as that of the class they belong to.
 Constructors are executed when an object is declared.
 Constructors have neither return value nor void.
 Though constructors are executed implicitly, they can be invoked explicitly.
 Constructors can have default values and can be overloaded.
 The constructor without arguments is called as default constructor.

PROGRAM:
/*CPP PROGRAM FOR DEFAULT CONSTRUCTOR*/

#include<iostream.h>
#include<conio.h>
class num
{
private:int a,b,c;
public:int x;
num(void);
void show()
{
cout<<"\nx="<<x<<"\na="<<a;
cout<<"\nb="<<b<<"\nc="<<c;
}
};
num::num(void)
{
cout<<"\n in default constructor";
x=5;
a=0;
b=4;
c=1;
}
void main()
{
clrscr();
num n;
n.show();
getch();
}
Prepared by G. VIJAYA KUMARI, Assoc.Prof.,
44
OBJECT ORIENTED PROGRAMMING THROUGH C + +

OUTPUT:
in default constructor
X=5
a=0
b=4
c=1
/*CPP PROGRAM FOR PARAMETERIZED CONSTRUCTOR*/
Program:
#include<iostream.h>
#include<conio.h>
class ex
{
private:int a,b;
public:ex(int m,int n);
void show()
{
cout<<"\na="<<a;
cout<<"\nb="<<b;
}
};
ex::ex(int m,int n)
{
a=m;
b=n;
}
void main()
{
clrscr();
ex e=ex(4,7);
ex e1(5,8);
e.show();
e1.show();
getch();
}
Output:
a=4
b=7
a=5
b=8

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


45
OBJECT ORIENTED PROGRAMMING THROUGH C + +

21. AIM: C + + PROGRAM FOR COPY CONSTRUCTOR


DESCRIPTION:
Constructors are of 3 types.
1. Default constructor: The constructor without arguments is called as default
constructor
2. Parameterized constructor: The constructor with some arguments is called as
parameterized constructor
3. Copy constructor: The constructor which can accept the arguments of any data type
including user defined data types.
Syntax for a copy constructor is
class num
{
private:
- -
- -
- -
public:
num( num&); // copy constructor
}

Overloaded constructors
CONSTRUCTOR DECLARATION OBJECT DECLARATION
(a) num (int m, float j, char k); (e) num x (4,5.45,’A’)
(b) num (int m, float j); (f) num y (1,2.2);
(c) num ( ); (g) num z;
(d) num (num &) (h) num k = z;

PROGRAM:
/*CPP PROGRAM FOR COPY CONSTRUCTOR*/
#include<iostream.h>
#include<conio.h>
class num
{
int n;
public:
num(){ }
num(int k)
{
n=k;
}
num(num &j)
{
Prepared by G. VIJAYA KUMARI, Assoc.Prof.,
46
OBJECT ORIENTED PROGRAMMING THROUGH C + +

n=j.n;
}
void show()
{
cout<<n;
}
};
void main()
{
clrscr();
num j(50);
num k(j);
num l=j;
cout<<"\n object j intialized n=";
j.show();
cout<<"\n object k initialized n=";
k.show();
cout<<"\n object l initialized n=";
l.show();
}

Output:
Object j initialized n=50
Object k initialized n=50
Object l initialized n=50

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


47
OBJECT ORIENTED PROGRAMMING THROUGH C + +
22. AIM: C + + PROGRAM FOR THIS POINTER
DESCRIPTION:
Similar to variables, objects also have an address. A pointer can point to a specified object.
The pointer ‘this’ points to hidden arguments (implicit arguments). Use of ‘this’ is now out
dated. Objects are used to invoke the non static member functions of the class.
C + + provides a pointer called ‘this’ which is transferred as an unseen parameter in all calls
to non static member functions. The keyword ‘this’ is a local variable that is always present
in the body of any non static member function.

PROGRAM:
/*CPP PROGRAM FOR THIS POINTER*/
#include<iostream.h>
#include<conio.h>
class number
{
int num;
public:void input()
{
cout<<"\n enter a number";
cin>>num;
}
void show()
{
cout<<"\n the minimum number is:"<<num;
}
number min(number t)
{
if(t.num<num)
return t;
else
return *this;
}
};
void main()
{
clrscr();
number n,n1,n2;
Prepared by G. VIJAYA KUMARI, Assoc.Prof.,
48
OBJECT ORIENTED PROGRAMMING THROUGH C + +

n1.input();
n2.input();
n=n1.min(n2);
n.show();
getch();
};
Output:
Enter a number:3
Enter a number:7
The minimum number is:3

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


49
OBJECT ORIENTED PROGRAMMING THROUGH C + +
23. AIM: C + + PROGRAM ILLUSTRATING OVERLOADING OF “++” OPERATOR
DESCRIPTION:
When an operator (increment/decrement) is used as prefix with object, its value is
incremented/decremented before operation, and on the other hand, the postfix use of
operator increments/decrements the value of variable after its use.
When ++ and – operators are overloaded, there exists no difference between the postfix
and prefix overloaded operator functions. The system has no way of determining whether
the operators are overloaded for postfix or prefix operation. Hence the operator must be
overloaded such a way that it will work for both prefix and postfix operations. The ++ and –
operator overloaded for prefix operation works for both prefix and postfix operations but
with warning message, ,but vice versa is not possible. To make
a distinction between prefix and postfix notations of operator, a new syntax is used to
indicate postfix operator overloading function.
operator ++ (int) //postfix notation
operator -- () // prefix notation

PROGRAM:
/* CPP PROGRAM ILLUSTRATING OVERLOADING OF ++ OPERATOR */
#include<iostream.h>
#include<conio.h>
class postfix
{
int c;
public:postfix()
{
c=0;
}
postfix(int x)
{
c=x;
}
postfix operator++()
{
return postfix(++c);
}
postfix operator++(int)
{
return postfix(c++);
}
Prepared by G. VIJAYA KUMARI, Assoc.Prof.,
50
OBJECT ORIENTED PROGRAMMING THROUGH C + +

void show()
{
cout<<c;
}
};
void main()
{
clrscr();
postfix A,B,C;
B=A++;
cout<<"\n B=";
B.show();
cout<<"\n A=";
A.show();
C=++A;
cout<<"\n C=";
C.show();
}

Output:
B=0
A=1
C=2

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


51
OBJECT ORIENTED PROGRAMMING THROUGH C + +
24. AIM: C + + PROGRAM ILLUSTRATING OVERLOADING OF NEW AND DELETE
OPERATOR
DESCRIPTION:
C + + has two operators for dynamic memory allocation and de allocation.
1. new: new operator is used to allocate memory for variables or for any object at run
time of program.
2. delete: delete operator is used to de allocate memory for variables or for any object
after completion of our program execution automatically.
Similar to other operators, ‘new’ & ‘delete’ operators can also be overloaded in C + +.

PROGRAM:
/* CPP PROGRAM ILLUSTRATING OVERLOADING OF NEW AND DELETE
OPERATOR*/
#include<iostream.h>
#include<conio.h>
const int ARRAY=10;
class vector
{
public:int *array1;
void *operator new(size_t size)
{
vector *d;
d=::new vector;
d->array1=new int[ARRAY];
return d;
}
void operator delete(void *vec)
{
vector *c;
c=(vector *)vec;
delete(int *)c->array1;
::delete vec;
}
void read()
{
for(int i=0;i<ARRAY;i++)
{

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


52
OBJECT ORIENTED PROGRAMMING THROUGH C + +

cout<<"vector["<<i<<"]=?";
cin>>array1[i];
}
}
int sum()
{
int sums=0;
for(int i=0;i<ARRAY;i++)
sums+=array1[1];
return sums;
}
};
void main()
{
clrscr();
vector *d=::new vector;
cout<<"enter vector data"<<endl;
d->read();
cout<<"sum of vector="<<d->sum();
delete d;
getch();
}
Output:
Enter vector data
Vector [0]=? 1
Vector[1]=? 1
Vector [2]=? 2
Vector [3]=? 3
Vector[4]=? 5
Vector [5]=? 6
Vector [7]=? 9
Vector[8]=? 7
Vector [9]=? 4
Sum of vector=38
Prepared by G. VIJAYA KUMARI, Assoc.Prof.,
53
OBJECT ORIENTED PROGRAMMING THROUGH C + +
25. AIM: C + +PROGRAM TO IMPLEMENT ABSTRACT CLASSES
DESCRIPTION:
A pure virtual function declared in the base class cannot be used for any operation. The
class containing the pure virtual function cannot be used to declare objects such classes are
known as “abstract classes or pure abstract classes”. The classes derived from the pure
abstract classes are required to re-declare the pure virtual function. All other derived classes
without pure virtual functions are called concrete classes. A pure virtual function is similar
to an unfilled container that the derived class is made to fill.

Declaration of pure virtual function


virtual void display() = 0; //pure function
Abstract classes are similar to skeleton on which new classes are designed to assemble well
designed class hierarchy. The programmer only extends them. When various programmers
work on same project, it is necessary to create common abstract base class for them.

PROGRAM:
/*CPP PROGRAM TO IMPLEMENT ABSTRACT CLASSES*/
#include<iostream.h>
#include<conio.h>
const int max=80;
class first
{
protected:
char name[max];
char cls[max];
public:
virtual void insert()=0;
virtual void show()=0;
};
class second:public first
{
protected: int fees;
public: void insert()
{
cout<<"enter name";
cin>>name;
cout<<"enter class";
cin>>cls;
cout<<"enter fees";
cin>>fees;
}

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


54
OBJECT ORIENTED PROGRAMMING THROUGH C + +

void show()
{
cout<<"\n name:"<<name<<"\n";
cout<<"class:"<<cls<<"\n";
cout<<"fees:"<<fees<<"\n";
}
};
void main()
{
clrscr();
second s1;
s1.insert();
s1.show();
getch();
}

Output:
enter name: ram
enter class: b.tech
enter fees: 10000
Name: ram
Class: b.tech
Fees: 10000

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


55
OBJECT ORIENTED PROGRAMMING THROUGH C + +
26. AIM: C + + PROGRAM TO IMPLEMENT MULTILEVEL, HYBRID AND MULTIPLE
INHERITANCES
DESCRIPTION:
Inheritance is one of the most useful and essential characteristic of object oriented
programming. The existing classes are the main components of inheritance. The new classes
are created from existing ones. The properties of existing classes are using a such method
are known as derived classes.
SYNTAX FOR CREATING A NEW CLASS:
Class derived class name: access specified base class name
{
----------------
----------------
};
Example:-
Class A
{
------------
------------
};
Class B: public A
{
------------
------------
};
TYPES OF INHERITANCE:
There are 6 types of inheritance.
1. Single inheritance 4. Multilevel inheritance
2. Multiple inheritance 5. Hybrid inheritance
3. Hierarchical inheritance 6. Multipath inheritance

1. SINGLE INHERITANCE:
A new class is created by using only one base class and the new class cannot be used as base
class to derive any new classes is known as single inheritance.

A is base class B is derived class B cannot be used as a base class to create a derived class.

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


56
OBJECT ORIENTED PROGRAMMING THROUGH C + +
2. MULTIPLE INHERITANCE:
Two or more base classes are used to create a new class is known as multiple inheritance
and the newly derived class should not be base class for any other new classes.

A B

Class A and class B are known as base classes and the derived class C inherits the properties
of both A and B and C should not be a base class for creating a new class.
3. HIERARCHIAL INHERITANCE:
By using a single base class we can able to create two or more derived classes and the
derived classes should not be base class for creating any new classes.

B C

A is the base class and B &C are the derived classes and B,C should not be a base class to
create other classes. In this B,C can inherit the properties of “A”.

4. MULTILEVEL INHERITANCE:
Single base class is used to derive a new class and the new class is again considered as base
class for creating a new derived class.

Here A is a base class and B is derived class from A and base class for C. C is a derived class
from B and C is also used as base class for creating new classes from it.
B can access the properties of A. C can access the properties of A &B.

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


57
OBJECT ORIENTED PROGRAMMING THROUGH C + +
5. HYBRID INHERITANCE:
Combination of two or more different types of inheritance is known as hybrid inheritance.
Combination of single and multiple inheritances is known as hybrid inheritance.

B C

D
Base class A is used to derive class B and C is again base class and D is the derived class from
B and C.
6. MULTIPATH INHERITANCE:
A new class is derived by using two derived classes which are derived from a single base
class is known as multipath inheritance.
A

B
C

PROGRAM:
/*CPP PROGRAM FOR MULTILEVEL INHERITANCE*/
#include<iostream.h>
#include<conio.h>
#include<string.h>
class A
{
protected: char cntry[20];
};
class B:public A
{
protected: char state[20];
};

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


58
OBJECT ORIENTED PROGRAMMING THROUGH C + +

class C: public B
{
char capital[20];
public: C()
{
strcpy(cntry,"INDIA");
strcpy(state,"ANDHRA PRADESH");
strcpy(capital,"GOGANNAMATAM");
}
void show()
{
cout<<"\n country:"<<cntry;
cout<<"\n state:"<<state;
cout<<"\n capital:"<<capital;
}
};
void main()
{
clrscr();
C c1;
c1.show();
getch();
}

Output:
Country: INDIA
State: ANDHRA PRADESH
Capital: GOGANNAMATAM

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


59
OBJECT ORIENTED PROGRAMMING THROUGH C + +

/*CPP PROGRAM FOR HYBRID INHERITANCE*/


PROGRAM:
#include<iostream.h>
#include<conio.h>
class A
{
protected:int a;
};
class B:public A
{
protected:int b;
};
class C
{
protected:int c;
};
class D:public B,C
{
int d;
public:D()
{
a=10;
b=20;
c=30;
d=40;
}
void show()
{
cout<<"\n a="<<a<<"\n b="<<b;
cout<<"\n c="<<c<<"\n d="<<d;
}
};

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


60
OBJECT ORIENTED PROGRAMMING THROUGH C + +

void main()
{
clrscr();
D d1;
d1.show();
getch();
}
Output:
A=10
B=20
C=30
D=40
/*CPP PROGRAM FOR MULTIPLE INHERITANCE*/
PROGRAM:
#include<iostream.h>
#include<conio.h>
class a
{
protected: int a;
};
class b
{
protected: int b;
};
class c:public a,b
{
int c;
public: c()
{
a=5;
b=13;
c=42;
}

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


61
OBJECT ORIENTED PROGRAMMING THROUGH C + +

void show()
{
cout<<"\n a="<<a<<"\n b="<<b<<"\n c="<<c;
}
};
void main()
{
clrscr();
c c1;
c1.show();
getch();
}

Output:
a=5
b=13
c=42

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


62
OBJECT ORIENTED PROGRAMMING THROUGH C + +
27. AIM: C ++ PROGRAM FOR VIRTUAL CLASS
DESCRIPTION:
Inheritance is one of the most useful and essential characteristic of object oriented
programming. The existing classes are the main components of inheritance. The new classes
are created from existing ones. The properties of existing classes are using a such method
are known as derived classes.
If a new class is derived by using two derived classes which are derived from a single base
class is known as multipath inheritance.
A

B
C

The properties of class A are inherited twice into class D in order to avoid the duplication we
must specify a base for D from which we inherit the properties of A. To identify that base
class we must specify the key word “virtual” for class B and class C.

PROGRAM:
/*CPP PROGRAM FOR VIRTUAL CLASS */
#include<iostream.h>
#include<conio.h>
class a
{
protected:int a;
};
class b:virtual public a
{
protected:int b;
};
class c:virtual public a
{
protected:int c;
};

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


63
OBJECT ORIENTED PROGRAMMING THROUGH C + +

class d:public b,c


{
int d;
public:d()
{
a=5;
b=10;
c=15;
d=20;
}
void show()
{
cout<<"\n a="<<a<<"\n b="<<b;
cout<<"\n c="<<c<<"\n d="<<d;
}
};
void main()
{
clrscr();
d d1;
d1.show();
getch();
}
Output:
a=5
b=15
c=20

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


64
OBJECT ORIENTED PROGRAMMING THROUGH C + +
28. AIM: C + + PROGRAM ILLUSTRATING OVERLOADING FUNCTION TEMPLATE
DESCRIPTION:
Template is a technique that allows a single function or class to work with different data
types. Using a template, we can create a single function that can process any type of data.
A template function also supports the overloading mechanism. It can be overloaded by a
normal function or a template function. While invoking these functions, an error occurs if no
accurate match is met. No implicit conversion is carried out in the parameters of template
functions. The compiler observes the following rules for choosing an appropriate function
when the program contains overloaded functions:
1. Searches for an accurate match of functions; if found, it is invoked
2. Searches for a template function through which a function that can be invoked with
an accurate match can be generate; if found, it is invoked.
3. Attempts a normal overloading declaration for the function.
4. In case no match is found, an error will be reported.

PROGRAM:
/*CPP PROGRAM ILLUSTRATING OVERLOADING FUNCTION TEMPLATE*/
#include<iostream.h>
#include<conio.h>
template<class A>
void show(A c)
{
cout<<"\n template variable c="<<c;
}
void show(int f)
{
cout<<"\n integer variable f="<<f;
}
void main()
{
clrscr();
show('c');
show(50);
show(20.5);
getch();
}

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


65
OBJECT ORIENTED PROGRAMMING THROUGH C + +

OUTPUT:
Template variable c=c
Integer variable f=50
Template variable c=20.5

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


66
OBJECT ORIENTED PROGRAMMING THROUGH C + +
29. AIM: C + + PROGRAM ILLUSTRATING CLASS TEMPLATE
DESCRIPTION:
Template is a technique that allows a single function or class to work with different data
types. Using a template, we can create a single function that can process any type of data;
that is, the formal arguments of a template function are of template (generic) type. They
can accept data of any type, such as int, float, and long.
Syntax: template<class T1, class T2>
Class name _of_class
{
Class declaration and definition
};

PROGRAM:
/*CPP PROGRAM ILLUSTRATING CLASS TEMPLATE*/
#include<iostream.h>
#include<conio.h>
template<class T1, class T2>
class data
{
public:data(T1 a,T2 b)
{
cout<<"\n a="<<a<<"\n b="<<b;
cout<<"\n-----------";
}
};
void main()
{
clrscr();
data<int,float>h(2,2.5);
data<int,char>i(40,'c');
data<float,int>j(3.14,20);
getch();
}

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


67
OBJECT ORIENTED PROGRAMMING THROUGH C + +

OUTPUT:
a=2
b=2.5
-----------
a=40
b=99
------------
a=3.14
b=20
------------

Prepared by G. VIJAYA KUMARI, Assoc.Prof.,


68

You might also like