Vous êtes sur la page 1sur 79

CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 1

MAM SCHOOL OF ENGINEERING









































CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 2

MAM SCHOOL OF ENGINEERING

CS 2209 OBJECT ORIENTED PROGRAMMING LAB
(Common to CSE & IT)


1. Design C++ classes with static members, methods with default arguments, friend
functions. (For example, design matrix and vector classes with static allocation,
and a friend function to do matrix-vector multiplication)

2. Implement complex number class with necessary operator overloading and type
conversions such as integer to complex, double to complex, complex to double
etc.

3. Implement Matrix class with dynamic memory allocation and necessary methods.
Give proper constructor, destructor, copy constructor, and overloading of
Assignment operator overloads the new and deletes operators to provide custom
dynamic allocation of memory.

5. Develop a template of linked-list class and its methods.

6. Develop templates of standard sorting algorithms such as bubble sort, insertion
sort, merge sort, and quick sort.

7. Design stack and queue classes with necessary exception handling.

8. Define Point class and an Arc class. Define a Graph class which represents
graph as a collection of Point objects and Arc objects. Write a method to find a
minimum cost spanning tree in a graph.

9. Develop with suitable hierarchy, classes for Point, Shape, Rectangle, Square,
Circle, Ellipse, Triangle, Polygon, etc. Design a simple test application to
demonstrate dynamic polymorphism and RTTI.

10. Write a C++ program that randomly generates complex numbers (use previously
designed Complex class) and writes them two per line in a file along with an
operator (+, -, *, or / ). The numbers are written to file in the format (a + ib). Write
another program to read one line at a time from this file, perform the
corresponding operation on the two complex numbers read, and write the result
to another file (one per line).








CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 3

MAM SCHOOL OF ENGINEERING

Department of Computer Science and Engineering
OBJECT ORIENTED PROGRAMMING LAB


LIST OF EXPERIMENTS






Ex No.


Title
1A Class with static Data Member
1B Class with Static Member Function
1C Function with Default Arugment
1D Matrix class using default argument, static data

members and friend function
2. Arithmetic Operations on Complex Number using Operator Overloading

3.
Dynamic Memory Allocation-Matrix using copy constructor and assignment
operator
4.
Overloading new and delete operator

5.
Template for Linked List Class and its Methods

6A Bubble sort using class template
6B Insertion sort using class template
6C Merge sort using class template
6D Quick sort using class template
7A Implementation of Stack-Exception Handling
7B Implementation of Queue-Exception Handling
8.
Demonstration of Dynamic Polymorphism and RTTI on Shape
Hierarchy

9 Finding Minimum Cost Spanning Tree

10 Operations on Complex Number using Files
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 4

MAM SCHOOL OF ENGINEERING

Exno: 1a

CLASS WITH STATIC DATA MEMBER


Aim
To write a c++ program to implement the concept of static data member in class.


Algorithm
Step 1: Start the program.
Step 2: Declare the static variable in the class.
Step 3: Increment the val;ue of static variable and store it in the another variable.
Step 4: Print the output of the static variable and the ordinary variable.
Step 5: Repeat the step 3,4 again and again.
Step 6: Stop the program.
Program:
#include<iostream.h>
class item
{
static int count;
int num;
public:
void getdata(int a)
{
num=a;
count++;
cout<<Number<<num;
}
void showcount()
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 5

MAM SCHOOL OF ENGINEERING

{
cout<<count;
cout<<count<<\ n;
}};
int item::count;
int main()
{
item a,b,c;
a.showcount();
b.showcount();
c.showcount();
a.getdata(20);
b.getdata(30);
c.getdata(40);
a.showcount();
b.showcount();
c.showcount(); }

OUTPUT:
count 0
count 0
count 0
Number 20
Number 30
Number 40
count 3
count 3
count 3

Result:
Thus the static data member of class is shared by all the instances of the class.
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 6

MAM SCHOOL OF ENGINEERING

Exno: 1b CLASS WITH STATIC MEMBER FUNCTION

Aim
To write a c++ program to implement the concept of static function in class.
Algorithm
Step 1: Start the program.
Step 2: Declare the static variable and static function in the class.
Step 3: Increment the value of static variable and store it in another variable.
Step 4: Print the output of the static variable and the ordinary variable.
Step 5: Repeat the step 3,4 again and again.
Step 6: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class name
{
static int count;
int num;
public:
void setnum()
{
cout<<"\ nInitialy count:"<<count;
/ / cin>>count;
num=++count;
}
void shownum()
{
cout<<"\ nNum:"<<num;
}

CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 7

MAM SCHOOL OF ENGINEERING

static void show();
};
int name::count;
void name::show()
{
cout<<"\ nCount:"<<count;
}
void main()
{
name n1,n2;
clrscr();
n1.setnum();
n1.shownum();
n2.setnum();
n2.shownum();
name::show();
name n3;
n3.setnum();
name::show();
n3.shownum();
getch();
}
Output:
Initial count=0
Num=1
Count=1
Initial count=1
Num=2
Count=2
Initial count=2
Count=3
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 8

MAM SCHOOL OF ENGINEERING

Num=3
Result:
Thus static member function of class is shared by all the instances of the class and a
static member functions cannot access auto members of a class.



























CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 9

MAM SCHOOL OF ENGINEERING

Exno: 1c

FUNCTION WITH DEFAULT ARGUMENT




Aim
To write a c++ program using function with default argument.

Algorithm:
Step 1: Start the program.
Step 2: Declare the function containing a character and an integer.
Step 3: Print a character for specified number of times by
i. Passing no arguments
ii. Passing one arguments
iii. Passing both the arguments.
Step 4: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class value
{
public:
void print(char='*',int=5);
};
void value::print(char y,int z)
{
int i;
for(i=1;i<=z;i++)
cout<<y;
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 10

MAM SCHOOL OF ENGINEERING

cout<<"\ n";
}
void main()
{
value v1,v2,v3,v4;
clrscr();
v1.print();
v2.print(67);
v3.print('+');
v4.print('-',6);
getch();
}

Output:
*****
Ccccc
+++++

Result:Thus in c++ an operation can be performed using functions with or without
passing arguments.

Ex.No.1d Matrix-Vector Multiplication using friend function



Aim:
To write C++ program to define matrix and vector class, to use
function with default argument and to do matrix-vector
multiplication using friend function.

Algorithm:
1. Declare vector Class
2. Define matrix Class
3. Declare friend function multiply() inside the matrix class
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 11

MAM SCHOOL OF ENGINEERING

4. Define vector Class
5. Declare friend function multiply() inside the vector class
6. Define getvector() function with for loop to get the elements for vector
7. Define disvector() function with for loop to display the contents of vector
8. Define getmatrix() function with nested for loops to get the matrix elements
9. Define dismatrix() function with nested for loops to display the matrix
10. Define the multiply() to multiply matrix and vector
a. No of columns in the matrix should be equal to no. of elements in the vector
b. Apply the matrix-vector multiplication mechanism:


a bx (a*x)+ (b* y)
` ` = `
c d)y) (c*x)+
(d * y))


c. Display the resultant matrix in the screen
11. Define main() to create objects and to call the defined functions.

Program
#include<iostream.h>
#include<conio.h>
class vector; / / class declaration - needed, because this class referred before it is defined in the
friend function.
class matrix
{ int m[3][3];
public:
void getmatrix(void);
void dismatrix(void);
friend void multiply(matrix &, vector &);
};
class vector
{ int v[10];
public:
/ / default argument is 3
void getvector(int n=3);
void disvector(void);
friend void multiply(matrix &, vector &);
};
void vector::getvector(int n)
{ int i;
cout<<"\ nEnter elements for vector one by one...\ n"; for(i=0;i<n;i++)
cin>>v[i];
}
void vector::disvector()
{ int i;
cout<<"\ nThe vector elements are...\ n";
for(i=0;i<3;i++)
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 12

MAM SCHOOL OF ENGINEERING

cout<<v[i]<<"\ t";
}
void matrix::getmatrix()
{ int i,j;
cout<<"\ nEnter the matrix...\ n";
for(i=0;i<3;i++)
for(j=0;j<3;j++)
cin>>m[i][j];
}
void matrix::dismatrix()
{ int i, j;
cout<<"\ nEntered matrix is...\ n"; for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
cout<<m[i][j]<<"\ t"; cout<<"\ n";
}
}
void multiply(matrix &m1, vector &v1)
{ int ans[3], i, j;
cout<<"\ nThe resultant matrix...\ n"; for(i=0;i<3;i++)
{
ans[i]=0;
for(j=0;j<3;j++)
ans[i]+=m1.m[i][j] * v1.v[j]; cout<<ans[i]<<"\ t";
}
}
void main()
{ matrix m1;
vector v1;
clrscr();
m1.getmatrix();
m1.dismatrix();
v1.getvector(); / / no argument, default value will be taken v1.disvector();
multiply(m1,v1);
getch();
}
OUTPUT
Enter the matrix...
2
2
2
2

2
2
2
2
2

CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 13

MAM SCHOOL OF ENGINEERING

Entered matrix is...
2 2 2
2 2 2
2 2 2

Enter elements for vector one by one...
2
2
2

The resultant matrix...
12 12 12



Result:
Thus a friend function is used for accessing the non-public members of a class.



Ex.No.2 Arithmetic Operations on Complex Number using Operator Overloading


Aim:
To write C++ program to define complex number class and to do
arithmetic operations on it using operator overloading.

Algorithm:
1. Define complex Class.
2. Define default constructor
3. Define conversion constructors
4. Declare friend function to overload >> and << operators
5. Declare other operator overloading functions
6. Define all the functions.
a. Addition:
(a+bi) + (x + yi) = ((a+x)+(b+y)i)
b. Subtraction:
(a+bi) - (x + yi) = ((a-x)+(b-y)i)
c. Multiplication:
(a+bi) * (x + yi) = (((a*x)-(b*y)) + ((a*y) + (x*b))i)
d. Division :
i.d=(x*x) + (y*y)
ii.(a+bi) / (x + yi) = (((a*x)+(b*y))/ d) + (((b*x)-(a*y))/ d)i
7. Create objects for complex class in main() function.
8. The arithmetic operators will invoke the overloaded operator
automatically and returns the result
9. Display the result using overloaded operators.
Program:
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 14

MAM SCHOOL OF ENGINEERING

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class complex
{
private:
float real;
float imag;
public:
complex()
{
real=imag=0.0;
}
complex(int r, int i)
{
real = r;
imag = i;
}
complex(double r, double i)
{
real = r;
imag = i;
}
friend istream& operator>>(istream &, complex &);
friend ostream& operator<<(ostream &, complex &); complex operator+(complex);
complex operator-(complex);
complex operator*(complex);
complex operator/ (complex);
friend double condou(complex t);
};
double condou(complex t)
{
return t.real;
}
istream& operator >>(istream &in, complex &c)
{
cout<<"\ nReal Part:"; in>>c.real;
cout<<"Imag Part:"; in>>c.imag;
return in;
}
ostream& operator<<(ostream &out, complex &c)
{
if (c.imag<0)
out<<c.real<<c.imag<<"i";
else
out<<c.real<<"+"<<c.imag<<"i"; return out;
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 15

MAM SCHOOL OF ENGINEERING

}
complex complex::operator+(complex c)
{
complex temp;
temp.real = real+c.real;
temp.imag = imag+c.imag; return temp;
}
complex complex::operator-(complex c)
{
complex temp;
temp.real = real-c.real;
temp.imag = imag-c.imag; return temp;
}
complex complex::operator*(complex c)
{
complex temp;
temp.real = real*c.real-imag*c.imag;
temp.imag = real*c.imag+imag*c.real;
return temp;
}complex complex::operator/ (complex c)
{
complex temp;
float qt;
qt = c.real*c.real+c.imag*c.imag;
temp.real = (real*c.real+imag*c.imag)/ qt;
temp.imag = (imag*c.real-real*c.imag)/ qt;
return temp;
}
void main()
{
complex c1, c2, c3,c4(4,9),c5(3.23004,4.666304444); double t;
clrscr();
t=condou(c5);
cout<<"\ nEnter complex number 1: "; cin>>c1;
cout<<"\ nEnter complex number 2: "; cin>>c2;
cout<<"\ nEnter complex numbers are:"; cout<<"\ nComplex 1: "<<c1;
cout<<"\ nComplex 2: "<<c2; c3=c1+c2;
cout<<"\ nResult of addition is:"<<c3; c3=c1-c2;
cout<<"\ nResult of subtraction is:"<<c3;
c3=c1*c2;
cout<<"\ nResult of multiplication is:"<<c3; c3=c1/ c2;
cout<<"\ nResult of division is:"<<c3;
cout<<"\ nInteger-->complex:"<<c4;
cout<<"\ nDouble-->complex:"<<c5;
cout<<"\ nConverted to double"<<t;
getch();
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 16

MAM SCHOOL OF ENGINEERING

}
OUTPUT
Enter complex number 1:
Real Part:20
Imag Part:10
Enter complex number 2:
Real Part:10
Imag Part:5
Enter complex numbers are:
Complex 1: 20+10i
Complex 2: 10+5i
Result of addition is:30+15i
Result of subtraction is:10+5i
Result of multiplication is:150+200i
Result of division is:2+0i
Integer-->complex:4+9i
Double-->complex:3.23004+4.666305i
Converted to double3.23004















Result:
Using the template operator overloaded with complex class is performed.

CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 17

MAM SCHOOL OF ENGINEERING

Ex.No.3 Matrix Class with Dynamic Memory Allocation




Aim:
To write C++ program to define matrix class with dynamic memory
allocation and to use constructor, destructor, copy constructor and
assignment operator overloading.

Algorithm:
1. Define matrix Class.
2. Define default constructor
3. Declare constructor for dynamic memory allocation
4. Declare matrix destructor
5. Declare the functions
6. Declare the assignment operator overloading function within the
class
7. Define all the functions.
8. Create objects for matrix class in main() function.
9. The memory for the objects is dynamically allocated.
10. Invoke copy constructor function
11. Invoke assignment operator overloading function.


Program:
/ / Matrix Class - Dynamic Memory Allocation
/ *Program to explain Constructor, Destructor, Copy constructor and Assignment operator
overloading*/
#include<iostream.h>
#include<conio.h>
class matrix
{ int **m;
int row, col;
public:
matrix()
{ row=col=0;
m=NULL;
}
matrix(int r ,int c); ~matrix();
void getmatrix();
void showmatrix();
matrix(matrix &m2); / / copy constructor
matrix& operator=(matrix &m2);
};
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 18

MAM SCHOOL OF ENGINEERING

matrix::~matrix()
{ for(int i=0;i<row;i++)
delete m[i];
delete m;
}
matrix::matrix(int r ,int c)
{ row = r;
col = c;
m = new int*[row];
for(int i=0;i<row;i++)
m[i]=new int[col];
}
matrix::matrix(matrix &m2)
{ cout<<"\ nCopy constructor invoked...\ n";
row = m2.row;
col = m2.col;
m = new int*[row];
for(int i=0;i<row;i++)
m[i]=new int[col];
for(i=0;i<row;i++)
for(int j=0;j<row;j++)
m[i][j]=m2.m[i][j];
}
matrix& matrix::operator=(matrix &m2)
{ cout<<"\ nAssignment Operator Overloading...\ n";
row = m2.row;
col = m2.col;
m = new int*[row];
for(int i=0;i<row;i++)
m[i]=new int[col]; for(i=0;i<row;i++)
for(int j=0;j<row;j++)
m[i][j]=m2.m[i][j];
return *this;
}
void matrix::getmatrix()
{ for(int i=0;i<row;i++)
for(int j=0; j<col; j++)
cin>>m[i][j];
}
void matrix::showmatrix()
{ for(int i=0;i<row;i++)
{ for(int j=0;j<col;j++)
cout<<"\ t"<<m[i][j]; cout<<"\ n";
}
}
void main()
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 19

MAM SCHOOL OF ENGINEERING

{ int r,c;
clrscr();
cout<<"\ nEnter rows and cols of the matrix...\ n"; cin>>r>>c;
matrix m1(r,c);
cout<<"\ nEnter the matrix elements one by one..."; m1.getmatrix();
cout<<"\ nEntered matrix is...\ n";
m1.showmatrix(); / / invoking copy constructor
matrix m2=m1;
cout<<"\ nResult of copy constructor is...\ n"; m2.showmatrix();
matrix m3;
m3=m1;
cout<<"\ nResult of assignment operator overloading...\ n"; m3.showmatrix();
getch();
}
Output

Enter rows and cols of the matrix...
2
2

Enter the matrix elements one by one...
4
4
4
4

Entered matrix is...
4 4
4 4

Copy constructor invoked...

Result of copy constructor is...
4 4
4 4

Assignment Operator Overloading...

Result of assignment operator overloading...
4 4
4 4




CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 20

MAM SCHOOL OF ENGINEERING















Result:
Thus the class with dynamic memory allocation is created and executed.
Ex.No.4 Overloading new and delete operator


Aim:
To write C++ program to overload new and delete operators to provide custom dynamic
memo allocation.

Algorithm:
1. Define vector Class.
2. Define new overloaded method
a. Accepts the size as input
b. Memory is created using malloc()
c. If there is no memory available, execution will be stopped.
d. Address is returned.
3. Define delete overloaded method
a. Object is removed from the memory using free()
4. Declare the functions read(), max() and sum()
5. Define all the functions.
6. Create objects for vector class in main() function.
7. The memory for the objects is dynamically allocated.
8. Invoke the functions dynamically.
9. Display the results.
10. Invoke the delete operator.

CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 21

MAM SCHOOL OF ENGINEERING

Program:
/ *Overloading new and delete operator using malloc and free*/ #include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class vector
{ private:
int *array;
public:
void *operator new(size_t size)
{
void *v;
cout<<"\ nOperator new invoked..."; v=malloc(size);
if(!v)
{
cout<<"Unable to allocate memory";
exit(0);
}
return v;
}
void operator delete(void* v)
{ cout<<"\ nOperator delete invoked...";
free (v);
}
void read(int);
int max(int);
int sum(int);
};
void vector::read(int s)
{
for(int i=0; i<s; i++)
{
cout<<"\ nEnter element "<<i+1<<":"; cin>>array[i];
}
}
int vector::sum(int s)
{
int tot=0;
for(int i=0; i<s; i++)
tot+=array[i];
return tot;
}
int vector::max(int s)
{
int max=0;
for(int i=0;i<s;i++)
if(array[i]>max)
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 22

MAM SCHOOL OF ENGINEERING

max = array[i];
return max;
}

void main()
{
int s;
clrscr();
cout<<"\ nEnter how many elements...";
cin >> s;
vector *vec = new vector;
cout<<"Enter vector data...\ n"; vec->read(s);
cout<<"\ nThe max is..."<<vec->max(s);
cout<<"\ nThe sum is..."<<vec->sum(s);
delete vec;
getch();
}







OUTPUT

Enter how many elements...
3

Operator new invoked...Enter vector data...

Enter element 1:45

Enter element 2:32

Enter element 3:67

The max is...67
The sum is...144
Operator delete invoked...





CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 23

MAM SCHOOL OF ENGINEERING



Result:
Thus the new and delete operator is overloaded along with dynamic memory allocation.
Ex.No.5 Template for Linked List Class and its Methods



Aim:
To write C++ program to develop a template for linked list class and its methods.

Algorithm:
1. Define struct node
2. Define list class with declaration of constructor and functions.
3. Define all the constructor and functions.
4. Length function will return the size of the list.
5. Makeempty() function will delete all the items in the list.
6. Insert() function will insert the item at the first position of the list.
7. Remove() function will remove item in the list which is entered by the user.
8. Create list object of list class in main() function.
9. Get the choice from the user
10. Invoke the functions appropriately.
11. Display the results.
Program :
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
template <class type>
struct node
{ type data;
node* next;
};
template<class type>
class list
{ public:
list();
int length(void) const;
void makeempty(void);
void insert(void);
void remove(void);
void display(void); private:
node<type>* linklist; int count;
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 24

MAM SCHOOL OF ENGINEERING

};
template <class type>
void list<type>::display(void)
{
node<type>* cur = linklist;
cout<<"\ nThe linked list is...\ n"; while(cur!=NULL)
{
cout<<cur->data<<"->"; cur=cur->next;
}
cout<<"NULL\ n";
}
template<class type>
list<type>::list()
{
count=0;
linklist=NULL;
}
template<class type>
int list<type>::length(void) const
{
return count;
}
template <class type>
void list<type>::makeempty(void)
{
node<type>* temp;
while(linklist !=NULL)
{
temp=linklist;
linklist=linklist->next; delete temp;
}
count=0;
cout<<"\ nNow List is empty...";
}
template <class type>
void list<type>::insert(void)
{
node<type>* temp; type item;
cout<<"\ nEnter the item to insert..."; cin>>item;
temp=new node<type>;
temp->data = item;
temp->next = linklist;
linklist=temp;
count++;
}
template<class type>
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 25

MAM SCHOOL OF ENGINEERING

void list<type>::remove(void)
{
node<type>* cur = linklist; type item;
cout<<"\ nEnter the item to remove..."; cin>>item;
node<type>* temp;
if(item==linklist->data)
{
temp = cur;
linklist=linklist->next;
}
else
{
while(!(item==(cur->next->data)))
cur=cur->next;
temp = cur->next;
cur->next = (cur->next)->next;
}
delete temp;
count--;
}

void main()
{ int ch;
list<int> list1;
clrscr();
while(1)
{
cout<<"\ n Single Linked List - Menu\ n";
cout<<"\ n 1.Insert \ n2.Delete\ n 3.Empty\ n 4.Exit\ n"; cout<<"\ nEnter your Choice... ";
cin>>ch;
switch(ch)
{ case 1:
list1.insert();
list1.display();
break;
case 2:
if(list1.length()>0)
{
list1.remove();
list1.display();
}
else
cout<<"\ nList Empty";
break;
case 3:
list1.makeempty();
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 26

MAM SCHOOL OF ENGINEERING

break;
case 4:
exit(0);
default:
cout<<"\ nInvalid Choice\ n";
}
}
}
Program :
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
template <class type>
struct node
{ type data;
node* next;
};
template<class type>
class list
{ public:
list();
int length(void) const;
void makeempty(void);
void insert(void);
void remove(void);
void display(void); private:
node<type>* linklist; int count;
};
template <class type>
void list<type>::display(void)
{
node<type>* cur = linklist;
cout<<"\ nThe linked list is...\ n"; while(cur!=NULL)
{
cout<<cur->data<<"->"; cur=cur->next;
}
cout<<"NULL\ n";
}
template<class type>
list<type>::list()
{
count=0;
linklist=NULL;
}
template<class type>
int list<type>::length(void) const
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 27

MAM SCHOOL OF ENGINEERING

{
return count;
}
template <class type>
void list<type>::makeempty(void)
{
node<type>* temp;
while(linklist !=NULL)
{
temp=linklist;
linklist=linklist->next; delete temp;
}
count=0;
cout<<"\ nNow List is empty...";
}
template <class type>
void list<type>::insert(void)
{
node<type>* temp; type item;
cout<<"\ nEnter the item to insert..."; cin>>item;
temp=new node<type>;
temp->data = item;
temp->next = linklist;
linklist=temp;
count++;
}
template<class type>
void list<type>::remove(void)
{
node<type>* cur = linklist; type item;
cout<<"\ nEnter the item to remove..."; cin>>item;
node<type>* temp;
if(item==linklist->data)
{
temp = cur;
linklist=linklist->next;
}
else
{
while(!(item==(cur->next->data)))
cur=cur->next;
temp = cur->next;
cur->next = (cur->next)->next;
}
delete temp;
count--;
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 28

MAM SCHOOL OF ENGINEERING

}

void main()
{ int ch;
list<int> list1;
clrscr();
while(1)
{
cout<<"\ n Single Linked List - Menu\ n";
cout<<"\ n 1.Insert \ n2.Delete\ n 3.Empty\ n 4.Exit\ n"; cout<<"\ nEnter your Choice... ";
cin>>ch;
switch(ch)
{ case 1:
list1.insert();
list1.display();
break;
case 2:
if(list1.length()>0)
{
list1.remove();
list1.display();
}
else
cout<<"\ nList Empty";
break;
case 3:
list1.makeempty();
break;
case 4:
exit(0);
default:
cout<<"\ nInvalid Choice\ n";
}
}
}
OUTPUT
Single Linked List - Menu

1.Insert
2.Delete
3.Empty
4.Exit

Enter your Choice... 1

Enter the item to insert...12
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 29

MAM SCHOOL OF ENGINEERING


The linked list is...
12->NULL

Single Linked List - Menu

1.Insert
2.Delete
3.Empty
4.Exit

Enter your Choice... 1

Enter the item to insert...10

The linked list is...
10->12->NULL
Single Linked List - Menu
1.Insert
2.Delete
3.Empty
4.Exit
Enter your Choice... 1
Enter the item to insert...10
The linked list is...
10->10->12->NULL
Single Linked List - Menu
1.Insert
2.Delete
3.Empty
4.Exit
Enter your Choice... 4










CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 30

MAM SCHOOL OF ENGINEERING


Result:
Thus the implementation of linked list to perform insertion and deletion is written
and executed.
Ex.No.6a Sorting Algorithms Using Templates--- Buble sort using templates



AIM


To write a C++ program for bubble sort using template.

Algorithm:

Step 1: Specify the template declaration and create a class as bubble.
Step 2: Declare the data members as size and *v as template variable.
Step 3: Allocate the memory space using default constructor.
Step 4: Destroy the memory space using destructor.
Step 5: Declare the member functionsas
void read() void
sort() void display()
Step 6: read() function is used to get the elements.

Step 7: sort() function is used to sort the elements.

7.1 Use the for loop to continue the iteration.

7.2 if statement is used to compare the element, if it is true, swap the
elements. Step 8: display() function is used to display the element.
Step 9: In the main, create the object using the following syntax:

classname<datatype>object
Step10: Call the read() function, to get the elements.
Step11: Call the sort() function, to sort the elements.
Step12: Call the display() function, to display the sorted elements



CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 31

MAM SCHOOL OF ENGINEERING





Program:
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
template <class t>
class bubble
{t a[25];
public:
void get(int);
void sort(int);
void display(int);
};
template <class t>
void bubble <t>::get(int n)
{int i;
cout<<"\ nEnter the array elements:"; for(i=0; i<n;i++)
cin>>a[i];
}
template <class t>
void bubble <t>::display(int n)
{int i;
cout<<"\ n The sorted array is...\ n";
for(i=0;i<n;i++)
cout<<a[i]<<setw(10);
}
template <class t>
void bubble <t>::sort(int n)
{
int i,j;
t temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 32

MAM SCHOOL OF ENGINEERING

}
void main()
{
int n;
bubble<int> b1;
bubble<float> b2;
clrscr();
cout<<"\ n Bubble Sort on Integer Values...";
cout<<"\ n Enter the size of array:\ n";
cin>>n;
b1.get(n);
b1.sort(n);
b1.display(n);
cout<<"\ n Bubble Sort on Float Values...";
cout<<"\ n Enter the size of array:\ n";
cin>>n;
b2.get(n);
b2.sort(n);
b2.display(n);
getch();
}
OUTPUT

Bubble Sort on Integer Values...
Enter the size of array:
4

Enter the array elements:
34
56
78
12

The sorted array is...
12 34 56 78
Bubble Sort on Float Values...
Enter the size of array:
3

Enter the array elements:
90.7
56.7
34.6

The sorted array is...
34.599998 56.700001 90.699997
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 33

MAM SCHOOL OF ENGINEERING

















Result:
Thus the elements are sorted using bubble sort technique.

Ex.No.6B
SortingAlgorithms Using Templates--- Insertion sort using templates



AIM
To write a C++ program for Insertion sort using template

Algorithm:

Step 1: Specify the template declaration and create a class as insertion.
Step 2: Declare the data members as size and *v as template variable.
Step 3: Allocate the memory space using default constructor.
Step 4: Destroy the memory space using destructor.
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 34

MAM SCHOOL OF ENGINEERING

Step 5: Declare the member functions as
void read() void
sort() void display()
Step 6: read() function is used to get the elements.

Step 7: sort() function is used to sort the elements.

7.1 Use the for loop to continue the iteration.

7.2 if statement is used to compare the element, if it is true, swap the
elements. Step 8: display() function is used to display the element.
Step 9: In the main, create the object using the following syntax:

classname<datatype>object

Step10: Call the read() function, to get the elements.
Step11: Call the sort() function, to sort the elements.
Step12: Call the display() function, to display the sorted elements.





Program

#include<iostream.h>
#include<conio.h>
template<class T>
class insert
{
T *v;
int s;
public:


insert(int x)
{
s=x;
v=new T[s];
}
void read(); void sort(); void display();
~insert()
{

delete v;
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 35

MAM SCHOOL OF ENGINEERING

}
};

template<class T>
void insert<T>::read()
{
for(int i=0;i<s;i++)
{
cin>>v[i];
}
}
template<class T>
void insert<T>::display()
{
for(int i=0;i<s;i++)
{
cout<<v[i]<<"\ t";
}
cout<<"\ n";
}

template<class T>
void insert<T>::sort()
{
for(int i=1;i<s;i++)
{
T t=v[i];
for(int j=i-1;j>=0 && t<v[j];j--)
v[j+1]=v[j];
v[j+1]=t;
display();
}
}
void main()
{clrscr(); int r;
cout<<"\ n\ nEnter the size:";
cin>>r;
insert<int>I(r);
cout<<"\ nEnter the Integer Elements:"; I.read();
I.sort();

insert<float>I1(r);
cout<<"\ n\ nEnter the Float Elements:"; I1.read();
I1.sort();

insert<char>I2(r);
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 36

MAM SCHOOL OF ENGINEERING

cout<<"\ n\ nEnter the Character Elements:"; I2.read();
I2.sort();

getch();
}







OUTPUT
Enter the size:5

Enter the Integer Elements:
89
90
45
1
3
89 90 45 1 3
45 89 90 1 3
1 45 89 90 3
1 3 45 89 90


Enter the Float Elements:
78
34.2
70
12.89
1
34.200001 78 70 12.89 1
34.200001 70 78 12.89 1
12.89 34.200001 70 78 1
1 12.89 34.200001 70 78


Enter the Character Elements:
r
t
y
w
q
r t y w q
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 37

MAM SCHOOL OF ENGINEERING

r t y w q
r t w y q
q r t w y

Result:Thus the elements are sorted using insertion sort technique.
Ex No.6c Sorting Algorithms UsingTemplates--- Merge sort using templates




Aim
To write a C++ program for merge sort using template.

Algorithm:

Step 1: Specify the template declaration and create a class as sort.
Step 2: Declare the data members as size and *v as template variable.
Step 3: Allocate the memory space using default constructor.
Step 4: Destroy the memory space using destructor.
Step 5: Declare the member functions as
void get()

void mergesort()

void merge()

void show()

Step 6: get() function is used to get the element.

Step 7: merge() sort function is used to divide the given element in equal
parts . Step 8: show() function is used to display the element.
Step 9: merge() function is used to perform sort operation.
Step10: In the main, create the object using the following syntax:
classname<datatype>object

Step11: Call the get() function, to input the elements.

Step12: Call the mergesort() and merge() function to perform divide and
conquer operation.
Step13: Call the show function to display the sorted elements.


CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 38

MAM SCHOOL OF ENGINEERING


Program:

#include<iostream.h>
#include<conio.h>

template<class T>
class Sort
{
private:
int n,l,r;
T *Array; T *b
public:

Sort();
void get();
void callMerge();
void mergeSort(T a[],int l,int r);
void merge(T c[],T d[],int l,int m,int r);
void copy(T b[],T a[],int l,int r);
void show();
~Sort();

};

template <class T> Sort<T>::Sort()
{
cout<<"\ nEnter the size of the array:";
cin>>n; Array=new T[n]; b=new T[n];
l=0;
r=n-1;
}
template <class T>
void Sort<T>::get()
{
cout<<"\ nEnter the Elements:\ n";
for(int i=0;i<n;i++)
cin>>Array[i];
}
template <class T>
void Sort<T>::callMerge()
{
(*this).mergeSort(Array,l,r);
}
template <class T>
void Sort<T>::mergeSort(T a[],int l,int r)
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 39

MAM SCHOOL OF ENGINEERING

{
if(l<r)
{
int i=(l+r)/ 2; mergeSort(a,l,i);

mergeSort(a,i+1,r); merge(a,b,l,i,r);

copy(b,a,l,r);
}
}
template <class T>
void Sort<T>::merge(T c[],T d[],int l,int m,int r)
{
int i=l,j=m+1,k=l;
while((i<=m) && (j<=r))
if(c[i]<=c[j])
d[k++]=c[i++];
else
d[k++]=c[j++];
if(i>m)
d[k++]=c[i];
else

for(int q=i;q<=m;q++)
d[k++]=c[q];
}
template <class T>
void Sort<T>::copy(T b[],T a[],int l,int r)
{
for(int i=l;i<=r;i++)
a[i]=b[i];
}
template <class T>
void Sort<T>::show()
{
cout<<"\ nThe Elements in the Sorted Array:\ t";
for(int i=0;i<n;i++,cout<<"\ t")
cout<<Array[i];
}
template <class T> Sort<T>::~Sort()
{
delete b;
delete Array;

}
void main()
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 40

MAM SCHOOL OF ENGINEERING

{
clrscr(); cout<<"\ n\ t\ t\ t************\ n";

cout<<"\ n\ t\ t\ tInteger Sort\ n";

cout<<"\ n\ t\ t\ t************\ n"; Sort<int> obj;
obj.get(); obj.callMerge(); obj.show();

cout<<"\ n";
cout<<"\ n\ t\ t\ t**********\ n"; cout<<"\ n\ t\ t\ tFloat

Sort\ n "; cout<<"\ n\ t\ t\ t**********\ n";

Sort<float> obj2;
obj2.get(); obj2.callMerge(); obj2.show();

cout<<"\ n";
cout<<"\ n\ t\ t\ t************\ n";

cout<<"\ n\ t\ t\ tCharater Sort\ n ";

cout<<"\ n\ t\ t\ t************\ n"; Sort<char> obj3;
obj3.get(); obj3.callMerge(); obj3.show();

getch();

}


OUTPUT
************
Integer Sort
************
Enter the size of the array:3
Enter the Elements:
23
45
67
The Elements in the Sorted Array: 23 45 67
**********
Float Sort
**********
Enter the size of the array:3
Enter the Elements:
78.2
12.8
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 41

MAM SCHOOL OF ENGINEERING

3.9
The Elements in the Sorted Array: 3.9 12.8 78.199997
************
Charater Sort
************
Enter the size of the array:4
Enter the Elements:
w
r
y
z
The Elements in the Sorted Array: r w y z



Result:Thus the elements are sorted using merge sort technique.





QUICK SORT USING TEMPLATE
Ex.No.6d






AIM:

To write a C++ program for quick sort using template.

Algorithm:

Step 1: Specify the template declaration and create a class as sort.

Step 2: Declare the data members n, lb and ub and *a as a template variable.
Step 3: Allocate the memory space using default constructor.
Step 4: Destroy the memory space using destructor.
Step 5: Declare the member functions as
void get()
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 42

MAM SCHOOL OF ENGINEERING


void callquick() void
quick() void show()
Step 6: get() function is used to get the element.

Step 7: callquick() function is used to call the quick function .

Step 8: quick() function is used to perform sort operation by using pivot
element . Step 9: In the main, create the object using the following syntax:
classname<datatype>object

Step10: Call the get() function, to input the elements.

Step11: Call the callquick() and quick() functions to perform sort
operation. Step12: Call the show() function to display the sorted elements.


Program:
#include<iostream.h>
#include<conio.h>
#include<process.h>

template<class T>
class Sort
{
private:
int n,lb,ub; T *a;
public:

void get();
void callquick();
void quick(int lb,int ub);
void show();
~Sort();

};

template <class T>
void Sort<T>::get()
{
cout<<"\ nEnter the size of the array:";
cin>>n;
a=new T[n];
cout<<"\ nEnter the Elements:";
for(int i=0;i<n;i++)
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 43

MAM SCHOOL OF ENGINEERING

cin>>a[i];
lb=0;
ub=n-1;
}

template <class T>
void Sort<T>::callquick()
{
(*this).quick(lb,ub);
}

template <class T>
void Sort<T>::quick(int lb,int ub)
{
T temp=0;
T flag=1,i=0,j=0,key=0;
if(lb<ub)
{
i=lb; j=ub+1; key=a[lb]; while(flag==1)
{
i=i+1;
while(a[i]<key)
i=i+1;
j=j-1;
while(a[j]>key)
j=j-1;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
else
flag=0;
}
temp=a[lb];
a[lb]=a[j];a[j]=temp;
show();
quick(lb,j-1);
quick(j+1,ub);
}
}

template <class T>
void Sort<T>::show()
{
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 44

MAM SCHOOL OF ENGINEERING

cout<<"\ nThe Elements in the Array:\ t";
for(int i=0;i<n;i++,cout<<"\ t")
cout<<a[i];
}

template <class T> Sort<T>::~Sort()
{
delete a;
}
void main()
{
clrscr(); Sort<int>obj; Sort<float>obj2;

Sort<char>obj3; int w;
do
{cout<<"\ n\ t\ t***************\ n"; cout<<"\ n\ t\ t

QUICK SORT\ n"; cout<<"\ n\ t\ t***************\ n";
cout<<"\ n\ t\ t1.Integer Sort\ n\ t\ t2.Float

Sort\ n\ t\ t3.Character Sort\ n\ t\ t4.Exit\ n";
cout<<"\ n\ t\ tEnter Ur choice:";
cin>>w;
switch(w)
{
case 1:

obj.get(); obj.callquick(); break;
case 2:

obj2.get(); obj2.callquick(); break;
case 3:
obj3.get(); obj3.callquick(); break;

case 4:
exit(0);
}
}while(w!=4);
getch();
}

OUTPUT
***************
QUICKSORT
**************

CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 45

MAM SCHOOL OF ENGINEERING

1.Integer Sort
2.Float Sort
3.Character Sort
4.Exit

Enter Ur choice:1

Enter the size of the array:5

Enter the Elements:23 45 11 78 1

The Elements in the
Array:
11 1 23 78 4
5 The Elements in the
Array:
1 11 23 78 4
5
The Elements in the
Array:
1 11 23 45 7
8
***************
QUICKSORT
***************

1.Integer Sort
2.Float Sort
3.Character Sort
4.Exit
Enter Ur choice:3
Enter the size of the array:5

Enter the Elements:r s k a q

The Elements in the Array: a q k r s The
Elements in the Array: a q k r s The
Elements in the Array: a k q r s
***************
QUICKSORT
***************

1.Integer Sort
2.Float Sort
3.Character Sort
4.Exit
Enter Ur choice:2
Enter the size of the array:5
Enter the Elements:2.2 4.5 1.1 7.8 0.1

The Elements in the
Array:
1.1 0.1 2.2 7.8 4.5
The Elements in the
Array:
0.1 1.1 2.2 7.8 4.5
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 46

MAM SCHOOL OF ENGINEERING

The Elements in the
Array:
0.1 1.1 2.2 4.5 7.8

***************
QUICKSORT
***************

1.Integer Sort
2.Float Sort
3.Character Sort
4.Exit

Enter Ur choice:4



Result:
Thus the elements are sorted using quick sort technique.













Stack class with Exception Handling
Ex no.7a




Aim:


CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 47

MAM SCHOOL OF ENGINEERING

To write a C++ program to implement stack using array.

Algorithm:

Step 1: Create a class as stk.

Step 2: Declare the data members as x, top, stack[10].

Step 3: Declare the member function as

stk()

void push() void
pop() void display()
Step 4: Default constructor is used to initialize the value to zero.
Step5: In the push function,
5.1 Check the stack for overflow.

5.2 Increment the top value.

5.3 Read the value to be pushed to the stack.

5.4 Push the value into the stack.

5.5 Display the pushed value. Step
6: In the pop function,
6.1 Check the stack for underflow.

6.2 Pop the value from the stack.

6.3 Decrement the top value.

6.4 Display the value that is popped from the stack. Step
7: display () function is used to display the stack content. Step
8: In the main, create the object for the class stk.
Step 9: In the do-while loop, it display the choice as push, pop and display.

9.1 If the choice is 1, call push function.

9.2 If the choice is 2, call pop function.

9.3 If the choice is 3, call display function.
Program
#include<iostream.h>
#include<conio.h>

class stk
{
int x,top,stack[10];
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 48

MAM SCHOOL OF ENGINEERING


public:
void push(); void pop(); void display();
};

void stk::push()
{
if(top==10)
cout<<"\ nSTACK FULL";
else

top=top+1;
cout<<"\ nENTER THE NUMBER TO BE PUSHED:";
cin>>x;
stack[top]=x;
cout<<"\ nTHE VALUE IS PUSHED INTO THE STACK
IS:"<<x;
}
void stk::pop()
{
if(top==0)
cout<<"\ nSTACK EMPTY\ n:";
else
{

x=stack[top];
top=top-1;
cout<<"\ nTHE VALUE RETREIVED FROM STACK IS:"<<x;

}
}
void stk::display()
{
cout<<"\ nCONTENTS OF STACK:";
for(int i=top;i>0;i--)

{
cout<<"\ n"<<stack[i]<<"\ t";
}
}
void main()
{
clrscr();
stk s; int a; cout<<"\ n\ t\ t\ t*****\ n";

CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 49

MAM SCHOOL OF ENGINEERING

cout<<"\ n\ t\ t\ tSTACK\ n";

cout<<"\ n\ t\ t\ t*****\ n";
do
{
cout<<"\ n\ n\ t\ t1.PUSH \ n\ t\ t2.POP

\ n\ t\ t3.DISPLAY
\ n\ t\ t4.EXIT";

cout<<"\ n\ t\ tENTER THE CHOICE:";
cin>>a;
switch(a)
{
case 1:s.push();
break;
case 2: s.pop();
break;
case 3:s.display();
break;
case 4:
exit(0);
default:
cout<<"\ nINVALID CHOICE";


}
}while(a<4);
getch();
}
OUTPUT
*************

STACK

**************
1.PUSH
2.POP
3.DISPLAY
4.EXIT
ENTER THE CHOICE:1

ENTER THE NUMBER TO BE PUSHED:12

THE VALUE IS PUSHED INTO THE STACK IS:12

CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 50

MAM SCHOOL OF ENGINEERING

1.PUSH
2.POP
3.DISPLAY
4.EXIT
ENTER THE CHOICE:1

ENTER THE NUMBER TO BE PUSHED:14

THE VALUE IS PUSHED INTO THE STACK IS:14

1.PUSH
2.POP
3.DISPLAY
4.EXIT
ENTER THE CHOICE:3

CONTENTS OF STACK:
14
12

1.PUSH
2.POP
3.DISPLAY
4.EXIT
ENTER THE CHOICE:4






CONTENTS OF STACK: 67
1.PUSH
2.POP
3.DISPLAY
4.EXIT
ENTER THE CHOICE:4

INVALID CHOICE





CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 51

MAM SCHOOL OF ENGINEERING




Result:
Thus stack is implemented to perform LIFO (Last In First Out) operation.


EX NO.7B Implementation of Queue-Exception Handling



AIM

To write a C++ program to implement queue using array.

Algorithm:

Step 1: Create a class as stk.

Step 2: Declare the data members as x, front, q[10], rear and result.
Step 3: Declare the member functions as
queue() void enq()
void dque() void
disp()
Step 4: Default constructor is used to initialize the front and rear value to
zero. Step5: In the enqueue function,
5.1 check the queue for overflow.

5.2 Read the value to be enqueued.

5.3 Increment the rear value.

5.4 Enqueue the value into the queue.

5.5 Display the enqueued value.
Step 6: In the dequeue function,
6.1 Check the queue for underflow.

6.2 Dequeue the value from the queue.

6.3 Increment the front.

6.4 Display the value that is dequeued from the queue.
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 52

MAM SCHOOL OF ENGINEERING

Step 7: disp() function is used to display the queue content.
Step 8: In the main, create the object for the class stk.
Step 9: In the do-while loop, it display the choice as enqueue, dequeue and display.

9.1 If the choice is 1, call enqueue function.

9.2 If the choice is 2, call dequeue function.

9.3 If the choice is 3, call display function.
Program:

#include<iostream.h>
#include<conio.h>

class queue
{
public:
int q[5],front,rear,x,result;
void enq(); void dque(); void disp(); queue()
{
front=0; rear=0;
}
};
void queue::enq()
{
if(rear>=5)
cout<<"\ nQueue overflow!!\ n";

else
{

cout<<"\ nEnter the number to be inserted: ";
cin>>x; rear++; q[rear]=x;
cout<<"\ nNumber pushed in the queue:"<<q[rear];
}
}

void queue::dque()
{
if(rear==0)
cout<<"\ nQueue underflow!!\ n";
else
{
if(front==rear)
{

CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 53

MAM SCHOOL OF ENGINEERING

front=0;
rear=0;

}
else

}
front++;
cout<<"\ nDeleted element is:";
result=q[front];
cout<<result;
}
void queue::disp()
{

if(rear==0)
cout<<"\ nQueue underflow!!\ n";
else
cout<<"\ nContents of queue is:";

for(int i=front+1;i<=rear;i++)
cout<<q[i]<<"\ t";
}
void main()
{
int c; queue qu; clrscr();
cout<<"\ n\ t\ t\ t*****\ n";

cout<<"\ n\ t\ t\ tQUEUE\ n";

cout<<"\ n\ t\ t\ t*****\ n";
do
{
cout<<"\ n\ n\ n\ t\ t\ t1.Insertion\ n\ t\ t\ t2.Deletion

\ n\ t\ t
\ t3.Display\ n\ t\ t\ t4.exit"; cout<<"\ n\ t\ tEnter

your choice:"; cin>>c;
switch(c)
{
case 1:
qu.enq();
break;
case 2:
qu.dque();
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 54

MAM SCHOOL OF ENGINEERING

break;
case 3:
qu.disp();
break;
case 4:
exit(0);
default:
cout<<"\ nInvalid choice!!\ n";
}
}while(c<=4); getch();
}

Output:


***** ***
QUEUE
*********
1.Insertion
2.Deletion
3.Display

Enter your choice:1

Enter the number to be inserted: 78

Number pushed in the queue:78

1.Insertion
2.Deletion
3.Display

Enter your choice:1

Enter the number to be inserted: 90

Number pushed in the queue:90

1.Insertion
2.Deletion
3.Display

Enter your choice:3

Contents of queue is:78 90

CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 55

MAM SCHOOL OF ENGINEERING

1.Insertion
2.Deletion
3.Display
Enter your choice:2

Deleted element is:78
1.Insertion
2.Deletion
3.Display
Enter your choice:3
Contents of queue is:90
1.Insertion
2.Deletion
3.Display
Enter your choice:4

Invalid choice!!






Result: Thus queue is implemented to perform FIFO (First In First Out) operation.

Hierarchical Inheritance with Virtual function and RTTI
Ex.No: 8


Aim:
To write a C++ program to draw rectangle, square and circle using
multiple inheritance with virtual function.
Algorithm:

Step 1: Create a class Point.

1.1 Declare the data members x and y.

1.2 Declare the member functions as
Point(int tempx,int tempy) int
getx()
int gety()

CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 56

MAM SCHOOL OF ENGINEERING

1.3 getx() function is used to return the value of x .

1.4 gety() function is used to return the value of y.
Step 2: Create a base class shape.
2.1 Declare the necessary data members.

2.2 Declare the member function as

virtual void draw()

Step 3: Create a derived class square. (Base class shape)

3.1 Create an abstract class.

3.2 Get the sides of square.

3.3 Draw the square using draw() function.

Step 4: Create a derived class rectangle. (Base class shape)

3.1 Create an abstract class.

3.2 Get the length and breadth of rectangle.

3.3 Draw the rectangle using draw() function.

Step 5: Create a derived class circle. (Base class shape)

3.1 Create an abstract class.

3.2 Get the radius of circle.

3.3 Draw the circle using draw() function.



Step 6: In the main,

6.1 Create the objects for point class.

6.2 Create a base pointer object for shape class.

6.3 Call the draw() function to draw the square, rectangle and circle.

Program

#include<iostream.h>
#include<conio.h>
#include<graphics.h>

class Point
{

public:

int x; int y; Point(){}
Point(int tempX, int tempY)
{

x=tempX;
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 57

MAM SCHOOL OF ENGINEERING

y=tempY;
}
int GetX()
{
return x;
}

int GetY()
{
return y;
}
friend ostream & operator<<(ostream & tempout,

Point & tempPoint)
{
tempout<<"("<<tempPoint.GetX()<<","<<tempPoint.GetY

()<<")";
return tempout;
}
};
class Shape
{
Point Position;
public:
Shape(){}
virtual void draw()
{
cout<<"shape is drawn";
}
};
class Square : public Shape
{

Point LeftBottom;
int Length;


public:
Square(){}
Square(Point tLeftBottom, int tLength)
{
LeftBottom=tLeftBottom; Length=tLength;
}
void draw()
{
as"<<Length<<"\ n";

cout<<"Square is drwan at"<<LeftBottom<<"and with

length

setcolor(14);
rectangle(LeftBottom.GetX(),LeftBottom.GetY(),LeftB

ottom.GetX()+Length,Lef tBottom.GetY()+Length);
}
};
class Rectangles : public Shape
{
Point LeftBottom, LeftTop, RightBottom, RightTop;
public:
Rectangles(){}
Rectangles(Point tLeftBottom, Point tLeftTop, Point
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 58

MAM SCHOOL OF ENGINEERING


tRightBottom, Point tRightTop)
{
LeftBottom=tLeftBottom; LeftTop=tLeftTop;

RightBottom=tRightBottom; RightTop=tRightTop;

}
void draw()
{
cout<<"Rectangle is drwan

at("<<LeftBottom<<","<<RightBottom<<")"<<"and"<<")"

<<LeftTop<<","<<RightTop<
<")\ n";
setcolor(4);


Y());



rectangle(LeftBottom.GetX(),LeftBottom.GetY(),Right

Top.GetX(),RightTop.Get

}
};


class Circle : public Shape
{


public:

Point Center;
int Radius;
Circle(){}
Circle(Point tCenter, int tRadius)
{
Center=tCenter; Radius=tRadius;
}
void draw()
{


cout<<"Circle is drawn at"<<" "<<Center<<" "<<"and

the radius is"<<Radius<<"\ n";
setcolor(5);
circle(Center.GetX(),Center.GetY(),Radius);



}
};
int main()
{
clrscr();
int gdriver = DETECT, gmode, errorcode;
initgraph(&gdriver, &gmode, "D:/ Tc/ BGI");

CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 59

MAM SCHOOL OF ENGINEERING

Point p1(100,200); Point p2(50,50); Point p3(100,300);

Square sq(p1,50);
Rectangles rect(p1,p2,p1,p2); Circle c(p3,50);

Shape*s;
s=&sq; s->draw();getch();

s=&rect;s->draw();getch(); s=&c;

s->draw();getch();

return 0;
}


Result:

Thus the virtual base class function is implemented in c++ program and area of
geometric figures are calculated.
















OUTPUT



Square is drawn at (100,200) and with length as 50
Rectangle is drawn at ((100,200), (100,200) ) and ( (50,50), (50,50) )
Circle is drawn at (100,300) and the radius is 50















CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 60

MAM SCHOOL OF ENGINEERING






























Ex.No. 9 Finding Minimum Cost Spanning Tree




Aim:
To define point class (node) and an arc class. To define a Graph class
which represents graph as a collection of Point objects and Arc objects.
And to write a method to find a minimum cost spanning tree in a graph.

Algorithm:
1. Define node class
2. Define arc class
3. Define graph class with a collection of node and arc class objects.
4. Get the no. of nodes
5. Get the edges with weight from the user.
6. Generate adjacency matrix
7. Apply prims algorithm to find minimum cost spanning tree
8. Display the minimum cost spanning tree



Program:
#include<iostream.h>
#include<conio.h>
#define MAX 10
int cost[MAX][MAX],MST[MAX][3];
int n;
void kruskal();
void main()
{
clrscr();
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 61

MAM SCHOOL OF ENGINEERING

cout<<"Enter the number of vertices:";
cin>>n;
cout<<"Enter cost adjacency matrix of the graph:";
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
if(i==j)
continue;
cout<<"is there edge

between"<<i<<"and"<<j<<"(Yes-pressl)";
int ch;
cin>>ch;
if(ch==1)
{
cout<<"Edge cost between vertex"<<i<<"and"<<j<<":";
cin>>cost[i][j];
}
else
cost[i][j]=100;
cost[j][i]=cost[i][j];
}
}
kruskal();
getch();
}
void kruskal()
{
int mine=100,a,b,i,j,k,q;
int no=n;
for(k=1;k<=no;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)
continue;
if(cost[i][j]<mine)
{
mine=cost[i][j];
a=i;
b=j;
}
}
}
MST[k][1]=a;
MST[k][2]=b;
MST[k][3]=mine;
cost[a][b]=cost[b][a]=100;
mine=100;
cout<<"\ n Minimum spanning tree:";
for(i=1;i<n;i++)
{
cout<<"\ n"<<MST[i][1]<<"<->"<<MST[i][2]<<":"<<MST[i

][3];
}
}
}



CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 62

MAM SCHOOL OF ENGINEERING

































OUTPUT:
Enter the number of vertices:4
Enter cost adjacency matrix of the graph:is there edge between1and2(Yes-pressl)1

Edge cost between vertex1and2:8
is there edge between1and3(Yes-pressl)0
is there edge between1and4(Yes-pressl)1
Edge cost between vertex1and4:7
is there edge between2and3(Yes-pressl)1
Edge cost between vertex2and3:9
is there edge between2and4(Yes-pressl)0
is there edge between3and4(Yes-pressl)1
Edge cost between vertex3and4:10

Minimum spanning tree:
1<->4:7
0<->0:0
0<->0:0
Minimum spanning tree:
1<->4:7
1<->2:8
0<->0:0
Minimum spanning tree:
1<->4:7
1<->2:8
2<->3:9
Minimum spanning tree:
1<->4:7
1<->2:8
2<->3:9


CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 63

MAM SCHOOL OF ENGINEERING







Result:
Thus the concept of graph along with minimum spanning tree is implemented.






Ex No. 10 Operations on Complex Number using Files


Aim:
To write a C++ program that randomly generates complex numbers and
write them two per line in a file along with an operator (+, -, *, or / ) in the
format (a + ib). To read one line at a time from this file, perform the
corresponding operation on the two complex numbers read, and write
the result to another file (one per line).
Algorithm:
1. Define complex class
2. Generate random numbers
3. Store the random numbers as complex number
4. Create an object to work with file
5. Open a file to write.
6. Write the complex numbers with the operator in a file.
7. Close the file.
8. Create an anther object to read the file.
9. Read the content and do the operation
10. Store the resultant matrix in another file.

Program

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
#include<time.h>
class complex
{public:
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 64

MAM SCHOOL OF ENGINEERING

int real;
int imag;
complex(int r,int i)
{real = r;
imag = i;
}
complex()
{real=imag=0; }
void display(void);
};
void complex::display(void)
{

cout<<real<<((imag<0)?"-i":"+i")<<imag<<"\ n"; }
void main()
{clrscr();
ofstream ocom("Complex.txt"); float real, imag;
time_t ti;
srand((unsigned) time(&ti)); real = rand()%100;
imag = rand()%100;
ocom<<"("<<real<<((imag<0)?"-i":"+i")<<imag<<")"<<"

+"; real = rand()%100;
imag = rand()%100;
ocom<<"("<<real<<((imag<0)?"-i":"+i")<<imag<<")"<<"\ n";
ocom.close();
ifstream icom("Complex.txt"); char no,t, ch,op;
icom>>no;
icom>>real;
icom>>ch;
icom>>no;
icom>>imag;
imag=(ch=='+')?imag:-imag; icom>>no;
icom>>op;
complex a(real,imag); icom>>no;
icom>>real;
icom>>ch;
icom>>no;
icom>>imag;
imag=(ch=='+')?imag:-imag;
complex b(real,imag); / / complex b is created

complex c;
switch(op)
{case '+':
c.real=a.real+b.real;
c.imag=a.imag+b.imag;
break;
case '-':
c.real=a.real-b.real;
c.imag=a.imag-b.imag;
break;
case '*':
c.real = (a.real*b.real)-(a.imag*b.imag);
c.imag = (a.real*b.imag)+(a.imag*b.real);
break;
case '/ ':
float qt;
qt = b.real*b.real+b.imag*b.imag;
c.real = (a.real*b.real+a.imag*b.imag)/ qt;
c.imag = (a.imag*b.real-a.real*b.imag)/ qt;
break;
default:
cout<<"\ nInvalid Operator";
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 65

MAM SCHOOL OF ENGINEERING

}
cout<<"\ nComplex 1:"; a.display();
cout<<"\ nComplex 2:"; b.display();
cout<<"\ nResultant Complex:"; c.display();
ofstream out("result.txt");
out<<"("<<c.real<<((c.imag<0)?"-i":"+i")<<c.imag<<"

)"; out.close();
}

Output

Complex 1:88+i56

Complex 2:83+i16

Resultant Complex:171+i72

Result:
Thus the c++ program for file handling to read and write the content in files was
implemented and executed.




Viva questions

1. What is the difference between interpreters and compilers?
Interpreters read through source code and translate a program, turning the
programmer's code, or program instructions, directly into actions. Compilers
translate source code into an executable program that can be run at a later time.

2. How do you compile the source code with your compiler?
Every compiler is different. Be sure to check the documentation that came with your
compiler.

3. What does the linker do?
The linker's job is to tie together your compiled code with the libraries supplied by
your compiler vendor and other sources. The linker lets you build your program in
pieces and then link together the pieces into one big program.

4. What are the steps in the development cycle?
Edit source code, compile, link, test, repeat.

5. What is the difference between the compiler and the preprocessor?
Each time you run your compiler, the preprocessor runs first. It reads through your
source code and includes the files you've asked for, and performs other
housekeeping chores. The preprocessor is discussed in detail on Day 18, "Object-
Oriented Analysis and Design."

6. Why is the function main() special?
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 66

MAM SCHOOL OF ENGINEERING

main() is called automatically, each time your program is executed.

7. What are the two types of comments, and how do they differ?
C++-style comments are two slashes (//), and they comment out any text until the
end of the line. C-style comments come in pairs (/* */), and everything between
thematching pairs is commented out. You must be careful to ensure you have
matchedpairs.


8. Can comments be nested?
Yes, C++-style comments can be nested within C-style comments. You can, in
fact,nest
C-style comments within C++-style comments, as long as you remember thatthe C++-
style comments end at the end of the line.

9. Can comments be longer than one line?
C-style comments can. If you want to extend C++-style comments to a second line,
you must put another set of double slashes (//).



10. What are the differences between the function prototype and the function
definition?
The function prototype declares the function; the definition defines it. The prototype
ends with a semicolon; the definition need not. The declaration can include the
keyword inline and default values for the parameters; the definition cannot. The
declaration need not include names for the parameters; the definition must.

11. Do the names of parameters have to agree in the prototype, definition, and call
to the function?
No. All parameters are identified by position, not name.

12. If a function doesn't return a value, how do you declare the function?
Declare the function to return void.

13. If you don't de
clare a return value, what type of return value is assumed?
Any function that does not explicitly declare a return type returns int.

14. What is a local variable?
A local variable is a variable passed into or declared within a block, typically a
function. It is visible only within the block.

15. What is scope?
Scope refers to the visibility and lifetime of local and global variables. Scope is
usually established by a set of braces.
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 67

MAM SCHOOL OF ENGINEERING


16. What is recursion?
Recursion generally refers to the ability of a function to call itself.



17. When should you use global variables?
Global variables are typically used when many functions need access to the same
data. Global variables are very rare in C++; once you know how to create static
class variables, you will almost never create global variables.

18.What is function overloading?
Function overloading is the ability to write more than one function with the same
name, distinguished by the number or type of the parameters.

19. What is polymorphism?
Polymorphism is the ability to treat many objects of differing but related types
without regard to their differences. In C++, polymorphism is accomplished by using
class derivation and virtual functions.



20. Is the declaration of a class its interface or its implementation?
The declaration of a class is its interface; it tells clients of the class how to interact
with the class. The implementation of the class is the set of member functions
stored--usually in a related CPP file.

21. What is the difference between public and private data members?
Public data members can be accessed by clients of the class. Private data members
can be accessed only by member functions of the class.

22. Can member functions be private?
Yes. Both member functions and member data can be private.

23. Can member data be public?
Although member data can be public, it is good programming practice to make it
private and to provide public accessor functions to the data.

24. Do class declarations end with a semicolon? Do class method definitions?
Declarations end with a semicolon after the closing brace; function definitions do
not.

25. What is the difference between the indirection operator and the address of
operator?
The indirection operator returns the value at the address stored in a pointer. The
address of operator (&) returns the memory address of the variable.
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 68

MAM SCHOOL OF ENGINEERING


26. What is the difference between a reference and a pointer?
A reference is an alias, and a pointer is a variable that holds an address. References
cannot be null and cannot be assigned to.

27. When must you use a pointer rather than a reference?
When you may need to reassign what is pointed to, or when the pointer may be
null.

28. What does new return if there is insufficient memory to make your new object?
A null pointer (0).

29. What is a constant reference?
This is a shorthand way of saying "a reference to a constant object."

30. What is the difference between passing by reference and passing a reference?
Passing by reference means not making a local copy. It can be accomplished by
passing a reference or by passing a pointer.

31. When you overload member functions, in what ways must they differ?
Overloaded member functions are functions in a class that share a name but differ
in the number or type of their parameters.

32. What is the difference between a declaration and a definition?
A definition sets aside memory, but a declaration does not. Almost all declarations
are definitions; the major exceptions are class declarations, function prototypes,
and typedef statements.
33. When is the copy constructor called?
Whenever a temporary copy of an object is created. This happens every time an
object is passed by value.

34. When is the destructor called?
The destructor is called each time an object is destroyed, either because it goes out
of scope or because you call delete on a pointer pointing to it.

35. How does the copy constructor differ from the assignment operator (=)?
The assignment operator acts on an existing object; the copy constructor creates a
new one.

36. What is the this pointer?
The this pointer is a hidden parameter in every member function that points to the
object itself.

37. How do you differentiate between overloading the prefix and postfix
increments?
The prefix operator takes no parameters. The postfix operator takes a single int
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 69

MAM SCHOOL OF ENGINEERING

parameter, which is used as a signal to the compiler that this is the postfix variant.

38. Can you overload the operator+ for short integers?
No, you cannot overload any operator for built-in types.

39. Is it legal in C++ to overload operator++ so that it decrements a value in your
class?
It is legal, but it is a bad idea. Operators should be overloaded in a way that is likely
to be readily understood by anyone reading your code.

40. What return value must conversion operators have in their declaration?
None. Like constructors and destructors, they have no return values.

41. What is a v-table?
A v-table, or virtual function table, is a common way for compilers to manage virtual
functions in C++. The table keeps a list of the addresses of all the virtual functions
and, depending on the runtime type of the object pointed to, invokes the right
function.





42. What is a virtual destructor?
A destructor of any class can be declared to be virtual. When the pointer is deleted,
the runtime type of the object will be assessed and the correct derived destructor
invoked.

43. How do you show the declaration of a virtual constructor?
There are no virtual constructors.

44. How can you create a virtual copy constructor?
By creating a virtual method in your class, which itself calls the copy constructor.

45. How do you invoke a base member function from a derived class in which
you've overridden that function?
Base::FunctionName();

46. How do you invoke a base member function from a derived class in which you
have not overridden that function?
FunctionName();

47. If a base class declares a function to be virtual, and a derived class does not use
the term virtual when overriding that class, is it still virtual when inherited by a
third-generation class?
Yes, the virtuality is inherited and cannot be turned off.
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 70

MAM SCHOOL OF ENGINEERING


48. What is the protected keyword used for?
protected members are accessible to the member functions of derived objects.

49. What is a down cast?
A down cast (also called "casting down") is a declaration that a pointer to a base
class is to be treated as a pointer to a derived class.

50. What is the v-ptr?
The v-ptr, or virtual-function pointer, is an implementation detail of virtual
functions.
Each object in a class with virtual functions has a v-ptr, which points to the virtual
function table for that class.

51. If a round rectangle has straight edges and rounded corners, your RoundRectclass
inherits both from Rectangle and from Circle, and they in turn both inheritfrom
Shape,
how many Shapes are created when you create a RoundRect?
If neither class inherits using the keyword virtual, two Shapes are created: one
forRectangle and one for Shape. If the keyword virtual is used for both classes,
onlyone
shared Shape is created.

52. If Horse and Bird inherit virtual public from Animal, do their constructors
initialize the Animal constructor? If Pegasus inherits from both Horse and Bird, how
does it initialize Animal's constructor?
Both Horse and Bird initialize their base class, Animal, in their constructors. Pegasus
does as well, and when a Pegasus is created, the Horse and Bird initializations of
Animal are ignored.

53. Declare a class Vehicle and make it an abstract data type.
class Vehicle
{virtual void Move() = 0;
}

54. If a base class is an ADT, and it has three pure virtual functions, how many of
these functions must be overridden in its derived classes?
None must be overridden unless you want to make the class non-abstract, in which
case all three must be overridden.

55. Can static member variables be private?
Yes. They are member variables, and their access can be controlled like any other.
If they are private, they can be accessed only by using member functions or, more
commonly, static member functions.

56. Show the declaration for a static member variable.
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 71

MAM SCHOOL OF ENGINEERING

static int itsStatic;

57. Show the declaration for a static function pointer.
static int SomeFunction();

58. Show the declaration for a pointer to function returning long and taking an
integer parameter.
long (* function)(int);

59. How do you establish an is-a relationship?
With public inheritance.

60. How do you establish a has-a relationship?
With containment; that is, one class has a member that is an object of another type.

61. What is the difference between containment and delegation?
Containment describes the idea of one class having a data member that is an object
of another type. Delegation expresses the idea that one class uses another class to
accomplish a task or goal. Delegation is usually accomplished by containment.

62. What is the difference between delegation and implemented-in-terms-of?
Delegation expresses the idea that one class uses another class to accomplish a
task or goal. Implemented-in-terms-of expresses the idea of inheriting
implementation from another class.


63. What is a friend function?
A friend function is a function declared to have access to the protected and private
members of your
class.

64. What is a friend class?
A friend class is a class declared so that all its member functions are friend
functions of your class.

65. If Dog is a friend of Boy, is Boy a friend of Dog?
No, friendship is not commutative.

66. If Dog is a friend of Boy, and Terrier derives from Dog, is Terrier a friend of Boy?
No, friendship is not inherited.

67. If Dog is a friend of Boy and Boy is a friend of House, is Dog a friend of House?
No, friendship is not associative.

68. Where must the declaration of a friend function appear?
Anywhere within the class declaration. It makes no difference whether you put the
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 72

MAM SCHOOL OF ENGINEERING

declaration within the public:, protected:, or private: access areas.

69. What is the insertion operator and what does it do?
The insertion operator (<<) is a member operator of the ostream object and is
usedfor
writing to the output device.

70. What is the extraction operator and what doesit do? The
extraction operator (>>) is a member operator of the istream object andis used for
writing to your program's variables.

71. What are the three forms of cin.get() and what are their differences?
The first form of get() is without parameters. This returns the value of the character
found, and will return EOF (end of file) if the end of the file is reached.
The second form of cin.get() takes a character reference as its parameter; that
character is filled with the next character in the input stream. The return value is an
iostream object.
The third form of cin.get() takes an array, a maximum number of characters to
get,and a
terminating character. This form of get() fills the array with up to one
fewercharacters
than the maximum (appending null) unless it reads the terminatingcharacter, in
which
case it immediately writes a null and leaves the terminatingcharacter in the buffer.

72. What is the difference between cin.read() and cin.getline()?
cin.read() is used for reading binary data structures.
getline() is used to read from the istream's buffer.


73. What is the default width for ouputting a long integer using the insertion
operator?
Wide enough to display the entire number.

74. What is the return value of the insertion operator?
A reference to an istream object.

75. What parameter does the constructor to an ofstream object take?
The filename to be opened.

76. What does the ios::ate argument do?
ios::ate places you at the end of the file, but you can write data anywhere in the file.

77. What is an inclusion guard?
Inclusion guards are used to protect a header file from being included into a
program more than once.
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 73

MAM SCHOOL OF ENGINEERING


78. How do you instruct your compiler to print the contents of the intermediate file
showing the effects of the preprocessor?
This quiz question must be answered by you, depending on the compiler you are
using.

79. What is the difference between #define debug 0 and #undef debug?
#define debug 0 defines the term debug to equal 0 (zero). Everywhere the word
debug is found, the character 0 will be substituted. #undef debug removes any
definition of debug; when the word debug is found in the file, it will be left
unchanged.

80. Name four predefined macros.
__DATE__, __TIME__, __FILE__, __LINE__

81. Why can't you call invariants() as the first line of your constructor?
The job of your constructor is to create the object. The class invariants cannot and
should not exist before the object is fully created, so any meaningful use of
invariants() will return false until the constructor is finished.

82. What is the difference between object-oriented programming and procedural
programming?
Procedural programming focuses on functions separate from data.
Objectorientedprogramming
ties data and functionality together into objects, and focuses on
theinteraction among the objects.

83. To what does "event-driven" refer?
Event-driven programs are distinguished by the fact that action is taken only in
response to some form of (usually external) simulation, such as a user's keyboard or
mouse input.

84. What are the stages in the development cycle?
Typically, the development cycle includes analysis, design, coding, testing,
programming, and interaction and feedback among these stages.

85. What is a rooted hierarchy?
A rooted hierarchy is one in which all the classes in the program derive directly or
indirectly from a single base class

86. What is a driver program?
A driver program is simply a function that is designed to exercise whatever objects
and functions you are currently programming.

87. What is encapsulation?
Encapsulation refers to the (desirable) trait of bringing together in one class all the
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 74

MAM SCHOOL OF ENGINEERING

data and functionality of one discrete entity.

88. What is the difference between a template and a macro?
Templates are built into the C++ language and are type-safe. Macros are
implemented by the preprocessor and are not type-safe.

89. What is the difference between the parameter to a template and the parameter
to a function?
The parameter to the template creates an instance of the template for each type. If
you create six template instances, six different classes or functions are created. The
parameters to the function change the behavior or data of the function, but only
one function is created.

90. What is the difference between a type-specific template friend class and a
general template friend class?
The general template friend function creates one function for every type of the
parameterized class; the type-specific function creates a type-specific instance for
each instance of the parameterized class.

91. Is it possible to provide special behavior for one instance of a template but not
for other instances?
Yes, create a specialized function for the particular instance. In addition to
creatingArray::SomeFunction(), also create Array::SomeFunction() to change the
behaviorfor integer arrays.

92. How many static variables are created if you put one static member into a
template class definition?
One for each instance of the class.


93. What is an exception?
An exception is an object that is created as a result of invoking the keyword throw.
It is used to signal an exceptional condition, and is passed up the call stack to the
first catch statement that handles its type.

94. What is a try block?
A try block is a set of statements that might generate an exception.

95. What is a catch statement?
A catch statement has a signature of the type of exception it handles. It follows a
try block and acts as the receiver of exceptions raised within the try block.

96. What information can an exception contain?
An exception is an object and can contain any information that can be defined
within a user-created class.

CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 75

MAM SCHOOL OF ENGINEERING

97. When are exception objects created?
Exception objects are created when you invoke the keyword throw.

98. Should you pass exceptions by value or by reference?
In general, exceptions should be passed by reference. If you don't intend to modify
the contents of the exception object, you should pass a const reference.

99. Will a catch statement catch a derived exception if it is looking for the base
class?
Yes, if you pass the exception by reference.

100. If there are two catch statements, one for base and one for derived, which
should come first?
catch statements are examined in the order they appear in the source code. The
first catch statement whose signature matches the exception is used.

101. What does catch(...) mean?
catch(...) will catch any exception of any type.

102. What is a breakpoint?
A breakpoint is a place in the code where the debugger will stop execution.

103 What is the difference between strcpy() and strncpy()?
strcpy(char* destination, char* source) copies source to destination, and puts a null
at the end of destination. destination must be large enough to accommodate
source, or strcpy() will simply write past the end of the array. strncpy(char*
destination char* source, int howmany) will write howmany bytes of source to
destination, but will not put a terminating null.


104. What does ctime() do?
ctime() takes a time_t variable and returns an ASCII string with the current time.
The time_t variable is typically filled by passing its address to time().

105. What is the function to call to turn an ASCII string into a long?
atol()
SOME MORE VIVA QUESTIONS
1.What are classes?
A class is a collection of objects of similar type. Once a class is defined any
number of objects can be created of that class.
Examples of classes are class of cars, class of pens, class of birds etc.

What are Instances?
Instances are essentially objects derived out of classes.
When an object is created for a particular class the process is called Instantiation.
In general, life time of object is nothing but the time between an object creation, till
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 76

MAM SCHOOL OF ENGINEERING

the object is no longer used and is destructed or freed.

2.What is object orientation?
It is a technique for system modeling. It offers a number of concepts

3.Pointer type: A Pointer is a variable which holds the address of another variable.

4.Const Qualifier: Const qualifier is used to prevent from accidental changes within
a program.

5.Differences between Structured Programming and OOP
In St.P emphasis is on What is happening. In OOP emphasis is on Who is being
affected.
Data move openly around the system. In St.P. In OOP the data and functions that
operate on the data are tied together
In St.P most fns share global data. In OOP data is hidden and cannot be accessed
by external functions.
In St.P, Large programs are divided to smaller programs known as functions, In
OOP they are divided into objects.

6.Enumerated Data type: It is a user-defined data type.
The syntax of enum statement is similar to that of struct
For Ex: enum shape{ circle, square, triangle};

7. New and Delete : (Memory Management Operators)
These are the unary operators to perform dynamic memory allocation and
deallocation
New operator is used to create objects. The General Form is:
Pointer-variable = new data-type; The general form of using delete
delete pointer-variable;
For Ex: delete p;
To free dynamically allocated array
delete [size] pointer-variable
For Ex: delete [10] p;
For Ex: int *p = new int;

8. Inline Functions:An inline function is a function that is expanded in line when it is
invoked
Inline function-header
{function body
}Ex: inline int square(int a)
{return a*a
};

9. Generic Functions
A generic function defines a general set of operations that can be applied to various
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 77

MAM SCHOOL OF ENGINEERING

types of data.. A generic function is created using the keyword template. The
general form of template function definition is
1. Template ret-type func-name(parameter list)
{ //function body }

10. Constructors and Destructors
Constructors:
1. C++ allows automatic initialization of objects when they are created. This is
performed through the use of a constructor function.
2. Constructor is a special function that is a member of the class and has the same
name as that class.
3. The Constructor is automatically called whenever an object of its associated class
is created.
4. A Constructor is declared and defined as follows
Destructors:
1. A destructor as the name implies is a complement of the constructor, used to
destroy objects.

2. It will be invoked implicitly by the compiler upon exit from program or function or
block
3. Local objects are destroyed when the block is left. Global objects are destroyed
when the program terminates.
4. It is a member function whose name is same as the class name but is preceded
by a tilde (~) operator. Ex : ~stack();
5. There are many reasons why a destructor may be needed. Ex: An object may
need to deallocate memory that it had previously allocated, or close a file that it
had opened.
6. A destructor never takes any argument nor does it return any value
7. It is a good practice to declare destructors


11. Class is syntactically similar to a struct. The only difference between them is
that by default all members are public in a struct and private in a class.

12. Friend Functions
1. Private members cannot be accessed from outside the class i.e by a non-member
function
2. C++ allows a non-member function to access private members of a class by
using a friend function.
3. A friend function need not be a member of any class.
4. To make an outside function friendly to a class, include its prototype within the
class, preceding it with the keyword friend.

13. Static Data Members(SDM)
1. Preceding a data members declaration with the keyword static tells the compiler
that only one copy of that variable will exist and that all objects of the class will
CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 78

MAM SCHOOL OF ENGINEERING

share that variable.
2. A static data member is initialized to zero when the first object of its class is
created. No other initialization is permitted.
3. Declaring a static data member is not defining it (means not allocating storage
for it). Remember class is a logical construct that does not have physical reality.
4. Defining a static data member is done outside the class by redeclaring the static
variable using the scope resolution operator .
5. SDM are normally used to maintain values common to entire class
Static Member Functions(SMF)
There are several restrictions placed on Static member functions.
1. A static function can have access to only other static members declared in the
same class.
2. Global functions and data may be accessed by SMF.
3. A SMF does not have a this pointer.
4. There cannot be a static version and non-static version of the same function
5. A SMF may not be virtual.
6. They cannot be declared as const or volatile
7. A static member function can be called using the class name as follows Classname
:: function-name;
8. Use is to preinitialize private static data before any object is created

14. This Pointer
When a member function is called, it is automatically passed an implicit argument
that is a pointer to the invoking object. This pointer is called this

15.Operator Overloading
The mechanism of giving additional meaning to an operator is known as operator
overloading.


16.INHERITANCE
1. The mechanism of deriving a new class from an old one is called Inheritance.
2. The concept of Inheritance provides the idea of reusability. This is basically done
by creating new classes, reusing the properties of the existing ones.
3. A class that is inherited is referred to as base class, and a class that inherits is
called the derived class.
4. Different types of Inheritance:

17.Protected Members
When a member of a class is declared as protected, that member is not accessible
by other nonmember elements of the program

18.A Virtual function: is a member function that is declared within a base class and
redefined by a derived class.To create a virtual function, precede the functions
declaration in the base class with the keyword Virtual.

CS2209 OBJECT ORINENTE D PROGRAMMING C++ Page 79

MAM SCHOOL OF ENGINEERING

19.. I/O Operations: C++ uses the concept of stream and stream classes to
implement the I/O Operations. A stream acts as an interface between the program
and I/O device.

20.What is Polymorphism?
It is generally ability to appear in many forms. In OOP, polymorphism refers to a
programming languages ability to process objects differently depending on their
data type or class.

21.What is Abstraction?
The process of picking out (abstracting) common features of objects and
procedures. A programmer would use abstraction. Abstraction is one of the most
important techniques in software engineering and it is closely related to two other
techniques- encapsulation and information hiding. All these three techniques are
used to reduce complexity.

Vous aimerez peut-être aussi