Вы находитесь на странице: 1из 44

Department of Computer Science and Engineering

GITAM Institute of Technology


GITAM UNIVERSITY

B.Tech. III Semester


(Syllabus w.e.f. 2015-16)

LTPC
EID 221 0 0 3 2

C++ LABORATORY

MANUAL

Prepared by:
Sri T.Srikanth
Smt. T. Kalaichelvi
Sri G.K Vasudevarao
Ms. Y. Divya Bharathi
Course Outcomes:

1. Map the basics of C language onto C++


2. Develop simple applications by applying Classes and Objects concepts
3. Examine the differences in function parameter passing techniques in C and
C++
4. Trace the working of Constructor functions in C++
5. Investigate the functioning of Constructors using dynamic memory
allocation
6. Develop applications by using object-oriented concepts Inheritance and
Polymorphism
7. Design applications by using Function overloading and Operator
overloading
8. Design applications using the concept of generic programming (templates)
9. Apply Exception handling in application development suitably
LAB CYCLE

1. Write a program that contains a function to exchange (swap) values of two arguments by
using pointers and References parameters.
2. Write a program to check the given string is palindrome or not using a private member
function.
3. Write a program to find transpose of 2-D matrix by allocating memory dynamically to the
matrix. Initialize and display contents of the matrix and deallocate memory.
4. Write a program to add corresponding elements of two 2-D matrices using friend
function. Create two classes each capable of storing one 2-D matrix. Declare the matrices
under private access specifier and access them outside the class.
5. Write a program for finding area of different geometric shapes (Circle, Rectangle and
Cube) using function overloading.
6. Write a Program to generate Fibonacci Series by using Constructor to initialize the Data
Members.
7. Write a program to add two matrices of same copy. Create two objects of the class and
each of which refers to one 2-D matrix. Use constructor to allocate memory dynamically
and use copy constructor to allocate memory when one array object is used to initialize
another.
8. Write a program to demonstrate single inheritance distinguishing public and private
derivation.
9. Write a program to illustrate the implementation of both Multilevel and Multiple (Hybrid)
inheritance.
10. Write a program to find transpose of a given matrix of mxn size using unary operator
overloading.
11. Write a program to add two matrices of mxn size using binary operator overloading.
12. Write a program to demonstrate the usage of virtual functions.
13. Write a program to sort a given set of elements using function template.
14. Write a program to search a key element in a given set of elements using class template.
15. Write a program to find average marks of the subjects of a student. Throw multiple
exceptions and define multiple catch statements to handle division by zero as well as array
index out of bounds exceptions.

****
1. Write a program that contains a function to exchange values of two
arguments by using pointers and References parameters.

Reference variable:

A reference variable is an alias, that is, another name for an already existing
variable. Once a reference is initialized with a variable, either the variable name
or the reference name may be used to refer to the variable.

Syntax:

int & reference_variable = variable_name;

Example:

int a = 10;
int & b = a; // b is a reference variable of a

References Pointers

Null Reference cannot be there Whereas Null Pointer can be there

Once a reference is initialized to an Pointers can be pointed to another


object, it cannot be changed to refer to object at any time
another object

A reference must be initialized when it is Pointers can be initialized at any time


created

Advantages of References:

1. Safer: Since references must be initialized, wild references like wild


pointers are unlikely to exist. It is still possible to have references that don’t
refer to a valid location.
2. Easier to use: References don’t need dereferencing operator to access the
value. They can be used like normal variables. ‘&’ operator is needed only at
the time of declaration. Also, members of an object reference can be
accessed with dot operator (‘.’), unlike pointers where arrow operator (->)
is needed to access members.
Program:

#include<iostream>
using namespace std;

void swap (int &a, int &b) // &a and &b are reference variables
{
int temp;
temp=a;
a=b;
b=temp;
}

void swap1(int *p, int *q) // *p and *q are pointer variables


{
int t;
t=*p;
*p=*q;
*q=t;
}

int main()
{
int i=5,j=10;
cout<<"Before Swapping I = "<<i<<" J = "<<j<<endl;
swap(i,j);
cout<<"After Swapping Using Reference I = "<<i<<" J = "<<j<<endl;
cout<<"Before Swapping I = "<<i<<" J = "<<j<<endl;
swap1(&i,&j);
cout<<"After Swapping Using Pointer I = "<<i<<" J = "<<j<<endl;
}
Output:
2. Write a program to check the given string is palindrome or not using a private
member function.

Private Member Function:


Usually member data are made private while functions (or methods) are
made public. There might be instances where you might want to make certain
functions private (i.e. you may not want the user to directly access these
functions). Private functions can only be called from within public member
functions. These functions are also called ‘helper functions’.

Syntax:
class class_name
{
private:
return_type function_name () // private member function declaration
{
---------;
}
public:
return_type function_name () // public member function declaration
{
---------;
function_name (); // private member function calling
}
};
int main()
{
class_name object_name;
object_name.function_name(); // public member function calling
}

Progam:
#include<iostream>
#include<string.h>
using namespace std;
class palinstr
{
private:
char input[30];
int checkpalin(char fninput[20]);
public:
void palin();
};

void palinstr::palin()
{
cout<<"Enter a String: ";
cin>>input;
if(checkpalin(input))
cout<<input<<" is a Palindrome\n";
else
cout<<input<<" is not a Palindrome\n";
}

int palinstr::checkpalin(char fninput[20])


{
int length,i;
length=strlen(fninput);
for(i=0; i< length/2; i++)
if(fninput[i]!=fninput[length-1-i])
return 0;
return 1;
}

int main()
{
palinstr sp;
sp.palin();
}

Output:
3. Write a program to find transpose of 2-D matrix by allocating
memory dynamically to the matrix. Initialize and display contents of the matrix
and deallocate memory

Dynamic memory allocation:

Dynamic memory is allocated using operator new. new is followed by a data type
specifier and, if a sequence of more than one element is required, the number of
these within brackets []. It returns a pointer to the beginning of the new block of
memory allocated.

Syntax:

1) pointer = new type


2) pointer = new type [number_of_elements]

The first expression is used to allocate memory to contain one single element of
type type.

The second one is used to allocate a block (an array) of elements of type type,
where “number of elements” is an integer value representing the amount of
memory required.

Creating memory for a matrix dynamically:


int rows = ..., cols = ...;
int** matrix = new int*[rows];
for (int i = 0; i < rows; ++i)
matrix[i] = new int[cols];

Deleting memory dynamically:


for (int i = 0; i < rows; ++i)
delete [] matrix[i];
delete [] matrix;

Program:
#include<iostream>
using namespace std;
class trans
{
int **a,**b;
int m,n;
public:
void initialize();
void transpose();
void display();
void deallocate();
};

void trans::initialize()
{
int i,j;
cout<<"No. of Rows and Columns: ";
cin>>m>>n;
a=new int *[m]; // create input matrix
for(i=0; i<m; i++)
a[i]=new int[n];

cout<<"Enter elements:\n";
for(i=0; i<m; i++)
for(j=0; j<n; j++)
cin>>a[i][j];

b=new int *[n]; // create transpose matrix


for(i=0; i<n; i++)
b[i]=new int[m];
}
void trans::transpose()
{
int i,j;
for(i=0; i<m; i++)
for(j=0; j<n; j++) // transpose is in 'b'
b[j][i]=a[i][j];
}
void trans::display()
{
int i,j;
cout<<"Transpose:\n";
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
cout<<b[i][j]<<" ";
cout<<"\n";
}
}
void trans::deallocate()
{
int i;
for(i=0; i<m; i++)
delete a[i];
delete a;
for(i=0; i<n; i++)
delete b[i];
delete b;
}
int main()
{
trans t;
t.initialize();
t.transpose();
t.display();
t.deallocate();
}
Output:
4. Write a program to add corresponding elements of two 2-D matrices
using friend function. Create two classes each capable of storing one 2-D matrix.
Declare the matrices under private access specifier and access them outside the
class

Friend Function:

A friend function of a class is defined outside that class scope but it has the right
to access all private and protected members of the class.

Syntax:
class class_name
{
private:
//private members declaration;
public:
return_type function_name () // public member function
{
---------;
}
friend return_type function_name (class_name object_name); // friend
function declaration
};
return_type function_name (); // friend function derivation
{
---------;
}
int main()
{
class_name object_name;
object_name.function_name(); // public member function calling
function_name(object_name); // friend function calling
}

Program:
include<iostream>
using namespace std;
class matrix2;
class matrix1
{
int a[5][5];
int m,n;
public:
void getmatrix1();
void putmatrix1();
friend void matrixsum(matrix1,matrix2);
};

void matrix1::getmatrix1()

{
int i,j;\
cout<<"MATRIX 1:\n";
cout<<"Rows and Columns: ";
cin>>m>>n;
cout<<"Enter elements:\n";
for(i=0;i<m;i++)
for(j=0;j<n;j++)
cin>>a[i][j];
}
void matrix1::putmatrix1()
{
int i,j;
cout<<"MATRIX 1:\n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
}

class matrix2
{
int b[5][5];
int m,n;
public:
void getmatrix2();
void putmatrix2();
friend void matrixsum(matrix1,matrix2);
};
void matrix2::getmatrix2()
{
int i,j;
cout<<"MATRIX 2:\n";
cout<<"Rows and Colums: ";
cin>>m>>n;
cout<<"Enter elements:\n";
for(i=0;i<m;i++)
for(j=0;j<n;j++)
cin>>b[i][j];
}

void matrix2::putmatrix2()
{
int i,j;
cout<<"MATRIX 2:\n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<b[i][j]<<" ";
cout<<endl;
}
}

void matrixsum(matrix1 g,matrix2 h)


{

int i,j;
if(g.m==h.m && g.n==h.n)
{
cout<<"SUM OF MATRICES:\n";
for(i=0;i<g.m;i++)
{

for(j=0;j<g.n;j++)
cout<<g.a[i][j]+h.b[i][j]<<" ";
cout<<endl;
}
}
else
cout<<"Dimensions are not same...Addition not possible";
}

int main()
{
matrix1 m1;
matrix2 m2;
m1.getmatrix1();
m2.getmatrix2();
m1.putmatrix1();
m2.putmatrix2();
matrixsum(m1,m2);
}

Output:
5. Write a program for finding area of different geometric shapes (Circle,
Rectangle and Cube) using function overloading

Function Overloading:
If any class has multiple functions with same names but different
parameters then they are said to be overloaded. Function overloading allows you
to use the same name for different functions, to perform, either same or different
functions in the same class.
Function overloading is usually used to enhance the readability of the
program. If you have to perform one single operation but with different number
or types of arguments, then you can simply overload the function.
Function overloading can be done in 2 ways.
i. By changing number of Arguments.
ii. By having different types of argument

Syntax:
return_type Function_Name (Parameter1, Parameter2)
{
-------;
}
return_type Function_Name (Parameter1, Parameter2, Parameter3)
{
-------;
}

int main()
{
function_name (Parameter1, Parameter2); // Function with 2 parameter will be called

function_Name (Parameter1, Parameter2, Parameter3); //Function with 3 parameter will be called


}

Program:
#include<iostream>
using namespace std;
float area(int r) // circle function
{
return (3.14159*r*r);
}
float area(float a) // cube function
{
return (6*a*a);
}
int area(int l,int b) // rectangle function
{
return (l*b);
}
int main()
{
int radius,length,breadth;
float side;
cout<<"Radius of Circle: ";
cin>>radius;
cout<<"Length of Side of Cube: ";
cin>>side;
cout<<"Length and Breadth of Rectangle: ";
cin>>length>>breadth;
cout<<"Area of Circle: "<<area(radius)<<"\n";
cout<<"Area of Cube: "<<area(side)<<"\n";
cout<<"Area of Rectangle: "<<area(length,breadth)<<"\n";
}

Output:
6. Write a program to generate Fibonacci Series using Constructor to
initialize the data members?
Constructor:

A class constructor is a special member function of a class that is executed


whenever we create new objects of that class.

A constructor will have exact same name as the class and it does not have any
return type at all, not even void. Constructors can be very useful for setting initial
values for certain member variables. It can be overloaded.

Syntax:

class class_name()
{
public:
class_name() //Constructor Member Function
{
-----------; //Initialization of the constructor
}
return_type function_name() //Normal Member Function
{
-----------;
}

};
int main()
{
class_name object_name; //Constructor Calling
object_name.function_name(); //Member Function Calling
}

Program:
#include<iostream>
#include<iomanip>
using namespace std;
class fibonacci
{
int n1,n2;
public:
fibonacci()
{
n1 = 0;
n2 = 1;
}
void series(int);
};

void fibonacci::series(int n)
{
int i,next;
cout<<setw(4) << n1 <<setw(4) << n2;
for(i=1; i<= n-2; i++)
{
next = n1 + n2;
cout<<setw(4) << next;
n1 = n2;
n2 = next;
}
}

int main()
{
fibonacci fib;
int n;
cout<< "FIBONACCI SERIES\n";
cout<< "How many numbers? ";
cin>> n;
fib.series(n);
}

Output:
7. Write a program to add two matrices of same copy. Create two objects of the
class and each of which refers one 2D matrix. Use constructor to allocate
memory dynamically and use copy constructor to allocate memory when one
array object is used to initialize another.

Copy Constructor:
The copy constructor is a constructor which creates an object by initializing it
with an object of the same class, which has been created previously. The copy
constructor is used to:
• Initialize one object from another of the same type.
• Copy an object to pass it as an argument to a function.
• Copy an object to return it from a function.
If a copy constructor is not defined in a class, the compiler itself defines one.If
the class has pointer variables and has some dynamic memory allocations, then it
is a must to have a copy constructor.

Syntax:
classname (const classname &obj)
{
// body of constructor
}
Here, obj is a reference to an object that is being used to initialize another object.

Program:
#include<iostream>
using namespace std;

class matrix
{
int **a;
public:
matrix() // Dynamic Constructor
{
int i,j;
a=new int*[3];
for(i=0; i<3; i++)
a[i]=new int[3];
cout<<"Enter elements for a 3x3 matrix:\n";
for(i=0; i<3; i++)
for(j=0; j<3; j++)
cin>>a[i][j];
}
matrix(matrix & x) // Copy Constructor
{
int i,j;
a=new int*[3];
for(i=0; i<3; i++)
a[i]=new int[3];
for(i=0; i<3; i++)
for(j=0; j<3; j++)
a[i][j]=x.a[i][j];
}
~matrix() // Destructor
{
int i;
for(i=0; i<3; i++)
delete a[i];
delete a;
}
void putmatrix();
friend void add(matrix,matrix);
};

void matrix::putmatrix()
{
int i,j;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
}

void add(matrix m1,matrix m2)


{
int i,j;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
cout<<m1.a[i][j]+m2.a[i][j]<<" ";
cout<<endl;
}
}

int main()
{
matrix obj1;
matrix obj2(obj1);
cout<<"Matrix 1 (and Matrix 2 also):\n";
obj1.putmatrix();
cout<<"SUM of the Matrices:\n";
add(obj1,obj2);
}

Output:
8. Derived class accessing private members of base class with public
inheritance
Inheritance:

One of the most important concepts in object-oriented programming is


that of inheritance. Inheritance allows us to define a class in terms of another
class, which makes it easier to create and maintain an application. This also
provides an opportunity to reuse the code functionality and fast implementation
time.

When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should
inherit the members of an existing class. This existing class is called the base
class, and the new class is referred to as the derived class.

A class can be derived from more than one classes, which means it can inherit
data and functions from multiple base classes. To define a derived class, we use a
class derivation list to specify the base class
private:

Private is the highest level of data-hiding. Not only are the functions and variables
marked private not accessible by code outside the specific object in which that
data appears, but private variables and functions are not inherited.

public:

The most open level of data hiding is public. Anything that is public is available to
all derived classes of a base class, and the public variables and data for each
object of both the base and derived class is accessible by code outside the class.
Functions marked public are generally those the class uses to give information to
and take information from the outside world.

protected:

Variables and functions marked protected are inherited by derived classes;


however, these derived classes hide the data from code outside of any instance of
the object. Even if you have another object of the same type as your first object,
the second object cannot access a protected variable in the first object. Instead,
the second object will have its own variable with the same name - but not
necessarily the same data. Protected is a useful level of access control for
important aspects to a class that must be passed on without allowing it to be
accessed.

/* Note: Either keyword public, protected or private is used in place of


access_specifier. */

Syntax:
class base_class_name
{
public:
base_class_nember() // base class member function
{
}
};
class derived_class_name : access_specifier base_class_name
{
public:
derived_class_nember() // derived class member function
{
}
};
int main()
{
derived_class_name object_name;
object_name.base_class_nember();
object_name.derived_class_nember();
}

Program:
#include<iostream>
using namespace std;
class emp
{
private:

void get() //Base_class_Private_Member_Function


{
cout<<"Enter the employee number:";
cin>>eno;
cout<<"Enter the employee name:";
cin>>name;
cout<<"Enter the designation:";
cin>>des;
}
public:
int eno;
char name[20],des[20];
void callget() //Base_class_Public_Member_Function

{
get(); //Base_class_Private_Member_Function_calling
}
};

class salary:public emp //Accessing Base_Class_Member as Public


{
float bp,hra,da,pf,np;

public:
void get1()
{
callget(); // Base_class_Public_Member_Function_calling
cout<<"Enter the basic pay:";
cin>>bp;
cout<<"Enter the Humen Resource Allowance:";
cin>>hra;
cout<<"Enter the Dearness Allowance :";
cin>>da;
cout<<"Enter the Profitablity Fund:";
cin>>pf;
}
void calculate()
{
np=bp+hra+da-pf;
}
void display()
{
cout<<"ENO\tENAME\tDESIGNATION\tBASICPAY\tHRA\tDA
\tPF\tNETPAY\n";
cout<<eno<<"\t"<<name<<"\t"<<des<<"\t\t"<<bp<<"\t\t"
<<hra<<"\t"<<da<<"\t"<<pf<<"\t"<<np<<"\n";
}
};

int main()
{
salary s;
s.get1(); // Derived_class_Public_Member_Function_calling
s.calculate();
s.display();
}
Output:
9. Write a C++ program to implement Hybrid Inheritance

Hybrid Inheritance:
Hybrid Inheritance is a method where one or more types of inheritance are
combined together and used.
Hybrid inheritance is a combination of multiple inheritance and multilevel
inheritance. A class is derived from two classes as in multiple inheritance.
However, one of the parent classes is not a base class. It is a derived class.
Syntax:
class base_class_name1 //Base Class1
{
protected:
Data Member;
public:
Member Fuction()
{
}
};
class derived_class_name1:public base_class_name1 // Derived class1 inherits
Base Class1 as Public
{
protected:
Data Member;
public:
Member Fuction()
{
}
};
class base_class_name2 //Base Class2
{
protected:
Data Member;
public:
Member Fuction()
{
}
};
class derived_class_name2: public derived_class_name1, public base_class_name2
// Derived class2 inherits Derived Class1 & Base Class2 as Public
{
protected:
Data Member;
public:
Member Fuction()
{
}

};
int main()
{
derived_class_name2 object_name;
object_name.Base_class1_Member Fuction();
object_name.Derived_class1_Member Fuction();
object_name.Base_class2_Member Fuction();
object_name.Derived_class2_Member Fuction();
}

Program:
#include<iostream>
using namespace std;
class stu //Base Class1
{
protected:
int rno;
public:
void get_no(int a)
{
rno=a;
}
void put_no(void)
{
cout<<"Roll No:"<<rno<<"\n";
}
};
class test:public stu // Derived class1 inherits Base Class1 as Public
{
protected:
float part1,part2;
public:
void get_mark(float x,float y)
{
part1=x;
part2=y;
}
void put_marks()
{
cout<<"Marks Obtained:"<<"\nPart1="<<part1<<"\n"<<"Part2="
<<part2<<"\n";
}
};
class sports //Base Class2
{
protected:
float score;
public:
void getscore(float s)
{
score=s;
}
void putscore(void)
{
cout<<"\nSports:"<<score<<"\n";
}
};
class result: public test, public sports // Derived class2 inherits Derived Class1 &
Base Class2 as Public
{
float total;
public:
void display(void);
};
void result::display(void)
{
total=part1+part2+score;
put_no();
put_marks();
putscore();
cout<<"\nTotal Score="<<total<<"\n";
}
int main()
{
result stu;
stu.get_no(123);
stu.get_mark(27.5,33.0);
stu.getscore(6.0);
stu.display();
return 0;
}

Output:
10. C++ program to find transpose of a given matrix of m*n size using binary
operator overloading

Operator overloading:
• The meaning of operators are already defined and fixed for basic types like:
int, float, double etc in C++ language.
• For example: If you want to add two integers then, + operator is used. But, for
user-defined types(like: objects), you can define the meaning of operator, i.e,
you can redefine the way that operator works.
• For example: If there are two objects of a class that contain string as its data
member, you can use + operator to concatenate two strings.
• Suppose, instead of strings if that class contains integer data member, then
you can use + operator to add integers.
• This feature in C++ programming that allows programmer to redefine the
meaning of operator when they operate on class objects is known as operator
overloading.
Syntax:
class < class_name>
{
Return_type operator <sign>(argument )
{
// body of function
}
};

Program:
#include<iostream>
using namespace std;
class matrix
{
int x[5][5],m,n;
public:
matrix(int a,int b)
{
m=a;n=b;
}
void get();
void put();
matrix operator !();
};

void matrix::get()
{
int i,j;
cout<<"\n Enter a matrix of order"<<m<<"x"<<n<<"\n";
for(i=0;i<m;i++)
for(j=0;j<n;j++)
cin>>x[i][j];
}
void matrix::put()
{
int i,j;

cout<<"\n The matrix after TRANSPOSE is :\n";


for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
cout<<x[i][j]<<"\t";
cout<<endl;
}
}
matrix matrix::operator !()
{
matrix c(n,m);
int i,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c.x[i][j]=x[j][i];
return c;
}
int main()
{
int m,n;
cout<<"\n Enter the order of matrix \t";
cin>>m>>n;
matrix a(m,n),c;
a.get();
c=!a;
c.put();
return 0;
}

Output:
11. Write a program to add two matrices of mxn size using binary operator
overloading.
Binary Operator Overloading:
• To overload a operator, a operator function is defined inside a class.
• Binary operators are addition (+) operator, subtraction (-) operator and
division (/) operator.

Syntax:
class < class_name>
{
Return_type operator <sign>(argument )
{
// body of function
}
};

Program:
#include<iostream>
using namespace std;

class matrixadd
{
int m, n, x[30][30];
public:
matrixadd() // Default Constructor
{
}
matrixadd(int a, int b) // Parameterized Constructor
{
m=a;
n=b;
}
void getdata();
void putdata();
matrixadd operator +(matrixadd);
};

void matrixadd:: getdata() //Input Function to get the values of first Matrix
{
cout<<"\nEnter values into the matrix :\n";
for(int i=0; i<m; i++)
{
for(int j=0; j<n;j++)
{
cin>>x[i][j];
}
}

matrixadd matrixadd::operator +(matrixadd b) //Operator Overloading


Function
{
matrixadd c(m,n);
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
c.x[i][j]= x[i][j] + b.x[i][j];
}
}
return c;
}

void matrixadd:: putdata() //Output Function to display


the result
{
cout<<"\nThe sum of the matrix is :\n";
for(int i=0; i<m; i++)
{
for(int j=0; j<n;j++)
{
cout<<x[i][j]<<"\t";
}
cout<<endl;
}
}

int main() // Main Function


{
int m,n;
cout<<"\nEnter the size of the array :\n";
cin>>m>>n;
matrixadd a(m,n) , b(m,n) , c;
a.getdata();
b.getdata();
c= a+b;
c.putdata();
return 0;
}

Output:
12. Write a program to demonstrate the usage of virtual functions.
Virtual Function:
• A virtual function is a member function that is declared within a base class and
redefined by a derived class.
• To create virtual function, precede the function’s declaration in the base class
with the keyword “virtual”.
• When a class containing virtual function is inherited, the derived class
redefines the virtual function to suit its own needs.
• Base class pointer can point to derived class object.
• In this case, using base class pointer if we call some function which is in both
classes, then base class function is invoked.
• But if we want to invoke derived class function using base class pointer, it can
be achieved by defining the function as virtual in base class, this is how virtual
functions support runtime polymorphism.

Syntax:
class <Base_class_name>
{
virtual ret-type func-name( )
{
// body of function
}
};

Program:
#include<iostream>
using namespace std;
class base
{
public:
void display()
{
cout<<"\n\t\tBase class display." ;
}
virtual void show()
{
cout<<"\n\t\tBase class show.";
}
};
class drived:public base
{
public:
void display()
{
cout<<"\n\t\tDrived class display.";
}
void show()
{
cout<<"\n\t\tDrived class show.";
}
};

int main()
{

base obj1;
base *p;
cout<<"\nP points to base class:\n" ;

p=&obj1;
p->display();
p->show();

cout<<"\n\nP points to drived class:\n";


drived obj2;
p=&obj2;
p->display();
p->show();
return 0;
}

Output:
13. Write a program to sort a given set of elements using function template.
Function Template
• Function Template gives the flexibility to a programmer for using any data type
in a function without rewriting the whole function for each data type again
and again.

Syntax:
template <class type>
ret_type func_name(parameter list)
{
// body of function
}

Program:
#include<iostream>
using namespace std;
template<class T>
void bubblesort(T a[], int n)
{
int i, j;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
T element;
element = a[i];
a[i] = a[j];
a[j] = element;
}
}
}
}

int main()
{
int a[6]={1,2,3,4,4,0};
char b[4]={'s','b','d','e'};
cout<<”Function Template used for Integers:\n”;
bubblesort(a,6);
cout<<"\nSorted Order Integers: ";
for(int i=0;i<6;i++)
{
cout<<a[i]<<"\t";
}
cout<<”\n\nFunction Template used for Characters.\n”;
bubblesort(b,4);
cout<<"\nSorted Order Characters: ";
for(int j=0;j<4;j++)
{
cout<<b[j]<<"\t";
}
return 0;
}
Output:
14. Write a program to search a key element in a given set of elements using
class template.
Class Template:
• A template is a blueprint or formula for creating a generic class or a function.
• In template we are creating type.
• Type is the placeholder type name, which will be specified when a class is
instantiated. You can define more than one generic data type by using a
comma-separated list.

Syntax:
template <class type>
class <class_name>
{
ret_type func_name(parameter list)
{
// body of function
}
};

Program:
#include<iostream>
#include<string.h>
using namespace std;
template<class T>
class arraysearch
{
T a[30],se;
int size;
public:
void get()
{
cout<<"\n Enter the size of array :";
cin>>size;
cout<<"\n Enter "<<size<<" elements :\n";
for(int i=0;i<size;i++)
{
cin>>a[i];
}
}
void search()
{
cout<<"\n Enter the elements to search:\n";
cin>>se;
int f=0;
for(int i=0;i<size;i++)
{
if(a[i]==se)
{
f=1;
cout<<"\n Element found at position:"<<i+1;
break;
}
}
if(f==0)
{
cout<<"\n Element not found.";
}
}
};
int main()
{
arraysearch <int> in;
arraysearch <char> ch;
cout<<"\n Searching integers :";
in.get();
in.search();
cout<<"\n\n Searching characters :";
ch.get();
ch.search();
return 0;
}
Output:
15. Write a program to find average marks of the subjects of a student. Throw
multiple exceptions and define multiple catch statements to handle division by
zero as well as array index out of bounds exceptions.
Exception Handling:
• Exceptions provide a way to transfer control from one part of a program to
another. C++ exception handling is built upon three keywords: try, catch, and
throw.
- throw: A program throws an exception when a problem shows up. This
is done using a throw keyword.
- catch: A program catches an exception with an exception handler at the
place in a program where you want to handle the problem. The catch
keyword indicates the catching of an exception.
- try: A try block identifies a block of code for which particular exceptions
will be activated. It's followed by one or more catch blocks.

Syntax:
try
{
// protected code
}
catch( ExceptionName e1 )
{
// catch block
}
catch( ExceptionName e2 )
{
// catch block
}
catch( ExceptionName eN )
{
// catch block
}

Program:
# include<iostream>
using namespace std;
int main()
{
int n,marks[10];
float avg=0,tot=0;
cout<<"\nEnter the no of subjects :";
cin>>n;
cout<<"\nEnter the marks of a student "<<n<<" students\n";
try
{
if(n>0&&n<=10)
{
for(int i=1;i<=n;i++)
{
cout<<"Enter marks of student"<<i<<":\t";
cin>>marks[i];
tot+=marks[i];
}
avg=tot/n;
cout<<"\nTotal marks :\t"<<tot<<"\nAverage of marks:\t"<<avg;
}
else if(n==0)
throw (0);
else if (n>10)
throw(10);
}
catch(int i)
{
cout<<"\n Divide by zero error...";
}
catch(double i)
{
cout<<"\n Array index out of bound";
}
}
Output:

Вам также может понравиться