Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 5 Muruga

Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

EE T46 Data Structures and Object Oriented Programming

DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING


Subject Name: Data Structures and Object Oriented Programming
Subject Code: EE T46

Prepared by:
Mr.J.Muruganandham, Assistant Professor/ EEE

Verified by: Approved by:

Unit V

Inheritance: Extending classes, Pointers, Virtual functions and polymorphism, File Handling,
Templates – Exception Handling .

2- MARKS
1. Define inheritance ?
Inheritance is the process of creating new classes from the existing classes. The new classes
are called derived classes. The existing classes are called base classes. The derived classes
inherit all the properties of the base class plus its own properties. The properties of inheritance
do not affect the base classes.
2. What are the types of inheritance?
 Single inheritance
 Multiple inheritance
 Hierarchial inheritance
 Multilevel inheritance.
 Hybrid inheritance
3. What are the advantages of using a derived class ?
 New classes can be derived by the user from the existing classes without any
modification.
 It saves time and money.
 It reduces program coding time.
 It increases the reliability of the program.
4. Define single inheritance.
If a derived class is derived from a base class then it is called single inheritance.

A B

Page 1
EE T46 Data Structures and Object Oriented Programming

5. What are the advantages of using a derived class ?


 New classes can be derived by the user from the existing classes without any
modification.
 It saves time and money.
 It reduces program coding time.
 It increases the reliability of the program.
6. Define multiple inheritance. (Nov 2015)

If a derived class is derived from more than one base class, then it is called multiple inheritance.

Class A Class B

Class C

7. Define hierarchical inheritance.


If two or more derived classes are derived from the same base class then it is known as
hierarchical inheritance.
A

B C D

8. Define multilevel inheritance.


If a derived class is derived from another derived class then it is known as multilevel
inheritance.
A

C
9. Define hybrid inheritance.
The combination of one or more types of inheritance is called hybrid inheritance.
A

B C

D
Page 2
EE T46 Data Structures and Object Oriented Programming

10. Define abstract class.


A class is said to be an abstract class if it satisfies the following conditions
 It should act as a base class
 It should not be used to create any objects
11. What is a virtual function? (May 2016)
A member function whose definition can be changed during run time is called virtual
function. The class which contains virtual function is called polymorphic class and it should be a
base class. Different versions for the virtual function should be present in different derived
classes with same name as virtual function name.
12. Define pure virtual function?
Pure virtual function is a virtual function with no body. The general form is :
Virtual void member-function-name ( ) = 0;
13. What are the properties of pure virtual function?
 It has no definition in the base class.
 We cannot create object for the class containing pure virtual function.
 Pure virtual function can be called through derived class objects.
 It acts as an empty bucket which has to be filled by its derived classes.
14. What are the rules for virtual functions?
 Virtual functions must be members of some class.
 They cannot be static members.
 They are accessed by using object pointers.
 A virtual function can be a friend of another class.
 We can have virtual destructors, but we cannot have virtual constructors.
 A virtual function in a base class must be defined even though it may not be used.
 A pointer to a derived class cannot point an object of base type.
 When a pointer points to a derived class, incrementing or decrementing will not
make it point to the next object of the derived class.
15. Define Polymorphism
It is the property of the same object to behave differently in different contexts given the
same message. A single function name can be used for various purposes and single operator is
used to achive multiple operations and the usage of either the function at the operator depends
on the context in such cases.
16. Define Compile time polymorphism
The compiler while compiling the program resolves the function call or the operator call.
This is known as compile time polymorphism
17. Define Runtime polymorphism
During multiple inheritance if the appropriate member function could be selected while the
program is running is known as Runtime polymorphism.
18. What are templates? (May 2015)
Templates are type-less programming mechanism to define classes and functions with
generic types. These classes and functions can work with any type.

Page 3
EE T46 Data Structures and Object Oriented Programming

19. Write about exception handling in C++. (Nov 2015)


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.
20. What Are Pointers? (May 2015)
A pointer is a variable whose value is the address of another variable. Like any variable
or constant, you must declare a pointer before you can work with it. The general form of a
pointer variable declaration is:
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of
the pointer variable. The asterisk you used to declare a pointer is the same asterisk

21. What is used of scope resulation operatiro (May 2016)


Scope resolution operator in c++ Scope resolution operator(::) is used to define a function
outside a class or when we want to use a global variable but also has a local variable with same
name.

Page 4
EE T46 Data Structures and Object Oriented Programming

11 Marks

1. Describe various types of inheritance with examples (May 2015)


The mechanism that allows us to extend the definition of a class without making any
physical changes to the existing class is inheritance. Inheritance lets you create new classes
from existing class. Any new class that you create from an existing class is called derived class;
existing class is called base class. The inheritance relationship enables a derived class to inherit
features from its base class. Furthermore, the derived class can add new features of its own.
Therefore, rather than create completely new classes from scratch, you can take advantage of
inheritance and reduce software complexity.
Syntax:
In order to derive a class from another, we use a colon (:) in the declaration of the
derived class using the following format :
class derived_class: memberAccessSpecifier base_class
{
...
};
Where derived_class is the name of the derived class and base_class is the name of the
class on which it is based. The member Access Specifier may be public, protected or private.
This access specifier describes the access level for the members that are inherited from the base
class.

Member Access
How Members of the Base Class Appear in the Derived Class
Specifier
Private members of the base class are inaccessible to the derived class.

Protected members of the base class become private members of the


Private derived class.

Public members of the base class become private members of the derived
class.

Private members of the base class are inaccessible to the derived class.

Protected members of the base class become protected members of the


Protected derived class.

Public members of the base class become protected members of the


derived class.

Private members of the base class are inaccessible to the derived class.

Protected members of the base class become protected members of the


Public derived class.

Public members of the base class become public members of the derived
class.

Page 5
EE T46 Data Structures and Object Oriented Programming

Different forms of Inheritance:


 Single inheritance
 Multiple inheritance
 Hierarchical inheritance
 Multilevel inheritance
 Hybrid inheritance
Single Inheritance
Single class is derived from a single base class. The derived class may inherit all or partial
properties of base class.
A

B
Syntax
class base class-name
{
//data members
//member functions
};
class derived-class-name: visibility-mode base-class-name
{
//data members
//member functions
};

Example
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student //Class Declaration
{
protected:
int regno,m1,m2,m3,m4,m5; //Data Member
Declaration
char name[20],dept[5];

public:
void getdata( ) //Function to get student details
{
cout<<"\nEnter the register number:";
cin>>regno;
cout<<"\nEnter the name:";
cin>>name;
cout<<"\nEnter the department:";
cin>>dept;
cout<<"\nEnter the mark 1:";
cin>>m1;
cout<<"\nEnter the mark 2:";
cin>>m2;

Page 6
EE T46 Data Structures and Object Oriented Programming

cout<<"\nEnter the mark 3:";


cin>>m3;
cout<<"\nEnter the mark 4:";
cin>>m4;
cout<<"\nEnter the mark 5:";
cin>>m5;
}
};

class exam: public student //Deriving new class from base class
{
private:
int total; //Data Member Declaration
char result[6];
float average;
public:

void calculation() //Function to calculate result of the student


{
total=m1+m2+m3+m4+m5;
average=float(total)/5;
if(m1>49 && m2>49 && m3>49 && m4>49 && m5>49)
{
strcpy(result,"Pass");
}
else
{
strcpy(result,"Fail");
}
}
void display() //Function to display student details
{
cout<<"\n\t\t\tSTUDENT DETAILS";
cout<<"\nRegister Number:"<<regno;
cout<<"\nName:"<<name;
cout<<"\nDepartment:"<<dept;
cout<<"\nMark 1:"<<m1;
cout<<"\nMark 2:"<<m2;
cout<<"\nMark 3:"<<m3;
cout<<"\nMark 4:"<<m4;
cout<<"\nMark 5:"<<m5;
cout<<"\nTotal:"<<total;
cout<<"\nAverage:"<<average;
cout<<"\nResult:"<<result;
}
};
int main()
{
exam ex; //Object declaration for derived class
cout<<"\n\t\t\t STUDENT INFORMATION";
ex.getdata( ); //Calling Base class function using derived object
ex.calculation( );

Page 7
EE T46 Data Structures and Object Oriented Programming

ex.display( );
}
Output: STUDENT DETAILS
Enter the register number 12345 Register Number:12345
Enter the name: xyz Name:xyz
Enter the department:ECE Department:ECE
Enter the mark 1: 50 Mark 1:50
Enter the mark 2:60 Mark 2:60
Enter the mark 3:70 Mark 3:70
Enter the mark 4:80 Mark 4:80
Enter the mark 5:50 Mark 5:50
Total:300
Average:60
Result:pass

Multiple inheritance
If a class is derived form morethan one base class, ut us know as multiple inheritance

Class A Class B

Class C

Syntax
class Derived-class-name : Base-class-name1, Base class-name2,…
{
Body of derived class
}
Example
class A
{
……………..
};
class B
{
……………..
};
class C : public A, public B
{
……………
};
Program
// Multiple Inheritance
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
protected:

Page 8
EE T46 Data Structures and Object Oriented Programming

int regno; //Data Member Declaration


char name[20],dept[5];
public:
void getdata() //Function to get student details
{
cout<<"\nEnter the register number:";
cin>>regno;
cout<<"\nEnter the name:";
cin>>name;
cout<<"\nEnter the department:";
cin>>dept;
}
};

class marks
{
protected:
int m1,m2,m3,m4,m5; //Data Member Declaration
public:
void getmarks() //Function to get student marks
{
cout<<"\nEnter the mark 1:";
cin>>m1;
cout<<"\nEnter the mark 2:";
cin>>m2;
cout<<"\nEnter the mark 3:";
cin>>m3;
cout<<"\nEnter the mark 4:";
cin>>m4;
cout<<"\nEnter the mark 5:";
cin>>m5;
}
};
//Deriving new class from more two base classes
class result: public student,public marks
{
private:
int total; //Data Member Declaration
float average;
char result[6];
public:
void calculation() //Function to calculate result of the student
{
total=m1+m2+m3+m4+m5;
average=float(total)/5;
if(m1>49 && m2>49 && m3>49 && m4>49 && m5>49)
{
strcpy(result,"Pass");
}
else
{
strcpy(result,"Fail");

Page 9
EE T46 Data Structures and Object Oriented Programming

}
}
void display() //Function to display student details
{
cout<<"\n\t\t\tSTUDENT DETAILS";
cout<<"\nRegister Number:"<<regno;
cout<<"\nName:"<<name;
cout<<"\nDepartment:"<<dept;
cout<<"\nMark 1:"<<m1;
cout<<"\nMark 2:"<<m2;
cout<<"\nMark 3:"<<m3;
cout<<"\nMark 4:"<<m4;
cout<<"\nMark 5:"<<m5;
cout<<"\nTotal:"<<total;
cout<<"\nAverage:"<<average;
cout<<"\nResult:"<<result;
}
};
int main()
{
clrscr();
result r; //Object declaration for derived class

cout<<"\n\t\t\t STUDENT INFORMATION";


r.getdata(); //Calling Base class function using derived object
r.getmarks(); //Calling Base class function using derived object
r.calculation();
r.display();

getch();
return 0;
}
Output: STUDENT DETAILS
Enter the register number 12345 Register Number:12345
Enter the name: xyz Name:xyz
Enter the department:ECE Department:ECE
Enter the mark 1: 50 Mark 1:50
Enter the mark 2:60 Mark 2:60
Enter the mark 3:70 Mark 4:80
Enter the mark 4:80 Mark 5:50
Enter the mark 5:50 Total:300
Average:60
Result:pass

Page 10
EE T46 Data Structures and Object Oriented Programming

Multilevel inheritance

The mechanism of deriving a class from another derived class is known as multilevel
inheritance. A

C
Syntax:
class Base-class-name
{
Body of Base class
};
class Derived-class-name1:Base-class-name
{
Body of derived class1;
};
class Derived –class-name2:Derived-class-name1
{
Body of derived class2;
};
Program
//Multilevel Inheritance: A -> B -> C
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student //Class Declaration
{
protected:
int regno; //Data Member Declaration
char name[20],dept[5];
public:
void getdata() //Function to get student details
{
cout<<"\nEnter the register number:";
cin>>regno;
cout<<"\nEnter the name:";
cin>>name;
cout<<"\nEnter the department:";
cin>>dept;
}
};

Page 11
EE T46 Data Structures and Object Oriented Programming

class marks: public student //Deriving new class from base class
{
protected:
int m1,m2,m3,m4,m5; //Data Member Declaration
public:
void getmarks() //Function to get student marks
{
cout<<"\nEnter the mark 1:";
cin>>m1;
cout<<"\nEnter the mark 2:";
cin>>m2;
cout<<"\nEnter the mark 3:";
cin>>m3;
cout<<"\nEnter the mark 4:";
cin>>m4;
cout<<"\nEnter the mark 5:";
cin>>m5;
}
};

class result: public marks //Deriving new class from another derived class
{
private:
int total; //Data Member Declaration
float average;
char result[6];
public:
void calculation() //Function to calculate result of the student
{
total=m1+m2+m3+m4+m5;
average=float(total)/5;
if(m1>49 && m2>49 && m3>49 && m4>49 && m5>49)
{
strcpy(result,"Pass");
}
else
{
strcpy(result,"Fail");
}
}
void display() //Function to display student details
{
cout<<"\n\t\t\tSTUDENT DETAILS";
cout<<"\nRegister Number:"<<regno;
cout<<"\nName:"<<name;
cout<<"\nDepartment:"<<dept;
cout<<"\nMark 1:"<<m1;
cout<<"\nMark 2:"<<m2;
cout<<"\nMark 3:"<<m3;
cout<<"\nMark 4:"<<m4;
cout<<"\nMark 5:"<<m5;
cout<<"\nTotal:"<<total;

Page 12
EE T46 Data Structures and Object Oriented Programming

cout<<"\nAverage:"<<average;
cout<<"\nResult:"<<result;
}
};

int main()
{
result r; //Object declaration for derived class
cout<<"\n\t\t\t STUDENT INFORMATION";
r.getdata(); //Calling Base class function using derived object
r.getmarks(); //Calling Base class function using derived object
r.calculation();
r.display();
}
Output: STUDENT DETAILS
Enter the register number 12345 Register Number:12345
Enter the name: xyz Name:xyz
Enter the department:ECE Department:ECE
Enter the mark 1: 50 Mark 1:50
Enter the mark 2:60 Mark 2:60
Enter the mark 3:70 Mark 3:70
Enter the mark 4:80 Mark 4:80
Enter the mark 5:50 Mark 5:50
Total:300
Average:60
Result:pass

Hierarchical inheritance
If anumber of classes are derived from a single base class, it is called ash hierarchial
inheritance
A

B C D

Syntax
class Base-class-name
{
-----------
};
class Derived-class-name1:Base-class-name
{
-----------
};
class Derived-class-nameN:Base-class-name
{
………..
};
Page 13
EE T46 Data Structures and Object Oriented Programming

Programm:
#include <iostream>
#include <conio.h>
using namespace std;
class person
{
char name[100],gender[10];
int age;
public:
void getdata()
{
cout<<"Name: ";
fflush(stdin); /*clears input stream*/
gets(name);
cout<<"Age: ";
cin>>age;
cout<<"Gender: ";
cin>>gender;
}
void display()
{
cout<<"Name: "<<name<<endl;
cout<<"Age: "<<age<<endl;
cout<<"Gender: "<<gender<<endl;
}
};

class student: public person


{
char institute[100], level[20];
public:
void getdata()
{
person::getdata();
cout<<"Name of College/School: ";
fflush(stdin);
gets(institute);
cout<<"Level: ";
cin>>level;
}
void display()
{
person::display();
cout<<"Name of College/School: "<<institute<<endl;
cout<<"Level: "<<level<<endl;
}
};

class employee: public person


{
char company[100];
float salary;

Page 14
EE T46 Data Structures and Object Oriented Programming

public:
void getdata()
{
person::getdata();
cout<<"Name of Company: ";
fflush(stdin);
gets(company);
cout<<"Salary: Rs.";
cin>>salary;
}
void display()
{
person::display();
cout<<"Name of Company: "<<company<<endl;
cout<<"Salary: Rs."<<salary<<endl;
}
};
int main()
{
student s;
employee e;
cout<<"Student"<<endl;
cout<<"Enter data"<<endl;
s.getdata();
cout<<endl<<"Displaying data"<<endl;
s.display();
cout<<endl<<"Employee"<<endl;
cout<<"Enter data"<<endl;
e.getdata();
cout<<endl<<"Displaying data"<<endl;
e.display();
getch();
return 0;
}

Output Employee
Student Enter data
Enter data Name: Mary White
Name: John Wright Age: 24
Age: 21 Gender: Female
Gender: Male Name of Company: Xyz Consultant
Name of College/School: Abc Academy Salary: $29000
Level: Bachelor
Displaying data
Displaying data Name: Mary White
Name: John Wright Age: 24
Age: 21 Gender: Female
Gender: Male Name of Company: Xyz Consultant
Name of College/School: Abc Academy Salary: $29000
Level: Bachelor

Page 15
EE T46 Data Structures and Object Oriented Programming

Hybrid inheritance

The process of applyin two or more types of inheritance to design a program is called
hybrid inheritance.
Base 1

Derived 1 Derived 2

Derived12

Syntax:
class Base-class-name1
{
………….
};
class Derived-class-name1:Base-class-name1
{
…………
};
class Base-class-name2:Base-class-name 1
{
…………
};
class Derived-class-name12:Derived-class-name1,Base-class-name2
{
………….
}
Programm:
#include <iostream>
using namespace std;

class dimension
{
protected:
int l,b;
public:
void get_dimension()
{
cout<<"Enter Length: ";
cin>>l;
cout<<"Enter breath: :";

}
};
class Rectangle:public dimension
Page 16
EE T46 Data Structures and Object Oriented Programming

{
protected:
float area;
public:
void rec_area()
{
get_dimendion();
area=l*b;
cout<<"Area of Rectangle:"<<area;
}
};

class Triangle: public dimension


{
protected:
float area;
public:
void Tri_area()
{
get_dimendion();
area=l*b;
cout<<"Area of Triangle:"<<area;
}
};

class process:public Rectangle, public Triangle


{
public:
void area()
{
rec_area();
Tri_area();
}
};

int main()
{
process p;
p.area();
}

2. Expain any two types of polymorphism

Write a C++ program which illustrate that the keyword ‘virtual’ can be used for functions
as well as classes (Nov 2015) (May 2015, May 2016)
Polymorphism

“Polymorphism is the property of the same object to behave differently in different contexts
given the same message”

Page 17
EE T46 Data Structures and Object Oriented Programming

Two types of polymorphism

1. Compile time polymorphism


2. Run time polymorphism

Polymorphis
m

Runtime
Compile Time

Function Operator Virtual


Overloading Overloading Functions

Compile Time Polymorphism


Achieved by function overloading and operator overloading
Function overloading: (Refer Unit 4: Question no:6)
A single function name can be used for various purposes (with different arguments)
Operator overloading: (Refer Unit 4: Question no:10)
Single operator is used to achieve multiple operations (with different type of operands)
Runtime polymorphism
 Run time polymorphism is achieved by virtual functions.
 Resolving function call at run time is known as runtime or late or dynamic binding.
 Runtime polymorphism allows selecting the suitable function at run time.

VIRTUAL FUNCTIONS
Definition:
A member function whose definition can be changed during run time is called virtual
function. The class which contains virtual function is called polymorphic class and it should be a
base class. Different versions for the virtual function should be present in different derived
classes with same name as virtual function name.
Rules for virtual function:
 Functions name must be proceeded by virtual keyword in the base class.
 Virtual constructors are not possible. Constructing a derived class object needs specific
construction of the base class sub object within.
 The function in the derived class must have same name as of the virtual function defined
in the base class and the same prototype.
 The function in the derived class need not be preceded by the virtual keyword.
 The virtual function must be defined in the base class, it may have an empty body.
 The virtual functions are members of the classes of the hierarchy.

Page 18
EE T46 Data Structures and Object Oriented Programming

Program
//Virtual Function
#include<iostream.h>
#include<conio.h>
class base // Base Class
{
public:
void show() //NON Virtual function
{
cout<<"base - Show \n";
}
virtual void display() //Virtual function
{
cout<<"base - display \n";
}
};

class derived: public base //Deriving new class from base class
{
public:
void show()
{
cout<<"derived - Show \n";
}
void display()
{
cout<<"derived - display \n";
}
};
int main()
{
base *ptr;
base b;
derived d;
cout<<"base object\n";
ptr=&b;
ptr->show();
ptr->display();
cout<<"Base pointer stores derived object address\n";
ptr=&d;
ptr->show();
ptr->display();
getch();
return 0;
}
Output:
base object
base - Show
base – display
base – Show
derived - display

Page 19
EE T46 Data Structures and Object Oriented Programming

Static vs Dynamic Binding

Static Binding Dynamic Binding

Static binding is method resolution dynamic binding refers to method resolution at run
at compile time time

Advantages of using virtual functions


Provides more flexibility
Eg: Generation of a cartoon movie
Latest News Telecast
Use of Virtual Functions
 Virtual functions will prove to be another tool for software reuse.
 Virtual functions supports late/dynamic binding

Pure Virtual Functions


C++ allows you to create a special kind of virtual function called a pure virtual function (or
abstract function) that has no body at all! A pure virtual function simply acts as a placeholder
that is meant to be redefined by derived classes.
Syntax
virtual void display ( ) =0;
Program
#include<iostream.h>
#include<conio.h>
#include<iostream.h>
#include<conio.h>
class base
{
private:
int x;
float y;
public :
virtual void getdata( );
virtual void display( );
};
class dev : public base
{
private:
int roll;
char name[20];
public :
void getdata( );
void display( );
};
void dev :: getdata( )
{
cout<<” Enter Roll of the Student “;
cin>> roll;
cout<<” Enter name of the student”;
Page 20
EE T46 Data Structures and Object Oriented Programming

cin>>name;
}

void dev :: display( )


{
cout<<”Name is :”<<name<<endl;
cout<<” Roll no is : ”<<roll <<endl;
}

void main( )
{
base * ptr;
dev obj;
clrscr( );
ptr = &obj;
ptr -> getdata( );
ptr -> display( );
getch( );
}
OUTPUT

Enter the roll no of the student: 111


Enter the name of the student : Kapil Dev

Name is : Kapil Dev


Roll no is : 111

3. Explain in details about the various Templates and it implementation (May 2016)

A template is a concept which enables us to define generic classes fand functions and
provides support for generic programming. It is used to create a family of class and function
Types of Templates:
 Function Template
 Class Template
Function Templates:
Function templates are special functions that can operate with generic type. Function
templates are those functions which can handle different data types without separate code for
each of them.
Syntax:
Template<Class T>
Return_type function_name(Arguments of type T)
{
//Body of function
}

Page 21
EE T46 Data Structures and Object Oriented Programming

Example:
#include <iostream>
#include <string>
using namespace std;
template <class T>
T Maximum (T a, T b)
{
if(a>b)
Return a;
else
Return b;
}
int main ( )
{
int i = 39;
int j = 20;
cout << "Maximum(i, j): " << Maxmum(i, j) << endl;

double f1 = 13.5;
double f2 = 20.7;
cout << "Maximim(f1, f2): " << Maximum(f1, f2) << endl;

char s1 = "Hello";
char s2 = "World";
cout << "Maximum(s1, s2): " << Maximum(s1, s2) << endl;
return 0;
}

Function Template with Multiple parameters:


If more than one generic data type in a function template is used, it should be declared as a
comma-separated list within the template specification .
Syntax:
Template<Class T1, class T2>
Return_type function_name(Arguments of type T1, T2)
{
//Body of function
}
Example:
#include <iostream>
#include <string>
using namespace std;
template <class T1, class T2>
void Maximum (T1 a, T2 b)
{
if(a>b)
cout<<” a is greater”;
else
cout<<”B is greater”;
}

Page 22
EE T46 Data Structures and Object Oriented Programming

int main ( )
{
int i = 39;
float j = 20.65;
Maximum(i, j):

int f1 = 13.5;
char f2 = ‘x’;
Maximim(f1, f2);

Float s1=20.6
char s2 = ‘z’
Maximum(s1, s2;

return 0;
}

Overloading of function template:


A template function can be overloaded either by template functions or ordinary function of it
name with the following resolution
1.call an ordinary function that has an exact match
2.call a template function that coluld be created whth n excat match
3.try normal overloading resolution to ordinary fuctions and call the one athat match

Example:
#include<iostream> Cout<<”Normal Fcn”;
Using namespace std; Cout<<”The value of x”;<<x;
Template<class T> }
Void show(T x) Int main( )
{ {
Cout<<”Template Fcn”; Show(10);
Cout<<”The value of x”;<<x; Show(10.5);
} Show(‘a’);
Void show(int x) Returen 0;
{ }
Class Template

A class created from a class template is called a template class.

Syntax:
Template <class a_type>
Class class_name
{
//class member specification
//with anonymous type T
// Wherever appropriate
}

Example:
#include <iostream>
using namespace std;
template<class T>

Page 23
EE T46 Data Structures and Object Oriented Programming

class math
{
T a;
public:
math(T x, T y)
{
a=x;
b=y;
}
void get_max()
{
if(a>b)
{
cout<<a<<" Max";
}
else
{
cout<<b<< " Max";
}
}
};

int main()
{
math<int>ob(10,20);
ob.get_max();
math<float>ob1(19.5,0200.36);
ob1.get_max();
math<Char>ob2(‘a’,’b’);
ob2.get_max();
return 0;
}
Class template with multiple paramenter:
If more then one generic data type in ca class template, it should be declared as a
comma-separated list within the template specification.
Syntax:
Template<Class T1, Class T2>
Class classname
{
//Body of the class
}
Example:
#include <iostream>
using namespace std;
template<class T1, class T2>
class math
{
T1 a;
T2 b;
public:
Page 24
EE T46 Data Structures and Object Oriented Programming

math(T1 x, T2 y)
{
a=x;
b=y;
}
void get_max()
{
if(a>b)
{
cout<<a<<" Max";
}
else
{
cout<<b<< " Max";
}
}
};

int main()
{
math<char, int>ob('a',0);
math<float, int>ob1(19.5,0200.36);
ob1.get_max();
return 0;
}

4. Explain in detail about exception handling in C++ (May 2016)


Exceptions are run time anomalies or unsusual conditions that a program may encounter
while executing.
Types of exception:
1. Synchronous Exceptions
The error such as out-of-range index and over-flow is called synchronous exceptions
2. Asynchronous exception
The errors that are caused by events beyond the control of the program is called
asynchronous exceptions

Exception handling is a mechanism that separates code that detects and handles exceptional
circumstances from the rest of your program. Ntoe that an exceptional circumstance is not
necessarily an error.
It perfom the following task:
 Find the problem(Hit the exception)
 Indorm that an error has occurred(Throw the exception)
 Receive the error information(Catch the exception)
 Take corrective action(Handle the exception)
Exception handling mechanism is made up of three keywords
1. Try:
The code that throus an exception should be enclosed in a try block(surrounded by
braces)

Page 25
EE T46 Data Structures and Object Oriented Programming

2. Throw:
When a exception is detected, it is thrown using a throw statement in the try block
3. Catch:
The exception that is thron in the try block has to be caught in catch block
Syntax :
Try
{
// Code to be executed
Throw(exception)
}
catch( )
{
//Code to be executed
}
Example program:
#include <iostream>
using namespace std;
int main()
{
float a,b;
cout<<"Enter the value of a&b";
cin>>a>>b;
try
{
if(b!=0)
{
cout<<"Result:"<<a/b;
}
else
{
throw(b);
}
}
catch(float i)
{
cout<<"Exception catches"<<b;
}
return 0;
}
Multipe catch statements:
When program segment has more than one condition to throw an exception, then the
multiple catch statement with single try statement is used

Page 26
EE T46 Data Structures and Object Oriented Programming

Syntax:
Try
{
Throw(type1 arg);
Throw(type2 arg);
Throw(type3 arg)
}
Catch(type1 arg)
{
}
Catch(type2 arg)
{
}
Catch(type3 arg)
{
}
Program:
Void test(int x)
{
try
{ if(x==1)
throw x;
else if(x==0)
throw ‘x’;
else if(x==-1)
throw 1.0;
}
catch(char c)
{ cout<<”caught a character”;
}
catch(int m)
{
Cout<<”caught a integer”;
}
catch(float f)
{ cout<<”caught a float”; }
}
Void main( )
{
Test(1);
Test(0);
Test(-1);
}

Page 27
EE T46 Data Structures and Object Oriented Programming

Rethrowing an Exception
The handler invokes the following throw statement without tany arguments to rethrow
the exception caught with out processing it. Throw; This causes the current exceotion to be
thrown to the next enclosing try/catch sequence and is caught by a catch statement listed aftaer
that enclosing try block.
Example:
#include<iostream>
Using namespace std;
Void fcn(int y)
{
Try
{
Cout<<”In try block fcn()”<<endl;
Throw y;
}
Catch(int)
{
Cout<<”in catch(int)”<<endl
Throw;
}
}

Int main ()
{
Try
{
Cout<<”In try block of main()”<<endl;
Fcn(5);
}
Catch(int)
{
Cout<<”In main() , catch(int)”<<endl;
}
}

Output:
With throw
In try block of main()
In try block of fcn()
In catch (int)
In main(), catch(int)
Without throw
In try block of main()
In try block of fcn()
In catch (int)

Page 28
EE T46 Data Structures and Object Oriented Programming

5. Explain in details about File Handling In C++ (Nov 2015)


Introduction to stream
 C++ still supports the entire C I/O system. However, C++ supplies a complete set of
object oriented I/O routines.
 To perform file I/O, you must include the header file fstream.h in your program.
 It contains declaration of several classes, including ifstream, ofstream and fstream.
These classes are derived from istream and ostream.
 In C++, a file is opened by linking it to a stream. There are three types of streams: input,
output, and input/output.
 To create an input stream, declare an object of type ifstream. To create an output
stream, declare an object of type ofstream.
 To create an input/output stream, declare an object of type fstream.
 Once you have created a stream, one way to associate it with a file is by using the
function open().

About function open()

 Prototype of function open is: open(filename, openmode mode);


 Here filename is the name of file, which can include a path specifier.
 The value of mode determines how the file is opened. It must be a value of type
openmode, which is an enumeration defined by ios that contains the following values:
 ios::app
 ios::ate
 ios::binary
 ios::in
 ios::out
 ios::trunc
 Including ios::app causes all output to that file to be appended to the end. This value can
be used only with files capable of output.
 Including ios::ate causes a seek to the end of the file to occur when the file is opened.
Although I/O operations can still occur anywhere with in the file.
 The ios::in value specifies that the file is capable of input. The ios::out value specifies that
the file is capable of output.
 The ios::binary value causes a file to be opened in binary mode. By default, all files are
opened in text mode.
 The ios::trunc value causes the contents of a preexisting file by the same name to be
destroyed and the file to be truncated to zero length

Reading and writing


To perform reading and writing you need to use member functions of one of the class
from ifstream, ofstream or fstream. Commonly used member function to read file content is
read() and member function to write file content is write()

Page 29
EE T46 Data Structures and Object Oriented Programming

Program for read a file:


#include<fstream.h>
#include<iostream.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>

int main ( )
{
char data[80],name[15];
ifstream infile; //Object Declaration For Input File Stream To Read In A File

cout<<"Enter File Name";


cin>>name;
infile.open(name);
if(!infile)
{
cout<<"File Does not Exist";
}
else
{
cout<<"\n";
while(!infile.eof())
{
infile>>data;
cout<<data<<endl;
}
infile.close();
}
infile.close();
getch();
}

Program for write a file:


#include<fstream.h>
#include<iostream.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>

int main ( )
{ char data[80],name[15];
ofstream outfile; //Object Declaration For Output File Stream To Write In A File

cout<<"Enter File Name";


cin>>name;
outfile.open(name);
cout<<"Enter contents to store in file (Enter $ to end):\n";
cin.ignore();
while(cin.getline(data,80))
{
Page 30
EE T46 Data Structures and Object Oriented Programming

if(strcmp(data,"$")!=0)
{
outfile<<data<<endl;
}
else
{
break;
}
}
outfile.close();
}

6. Explain in details about pointe concept in C++


Pointers is a derived data type that refers to another variable by stroing the variable’s
memory address rateher than data. A pointer is a variable whose value is the address of another
variable. Like any variable or constant, you must declare a pointer before you can work with it.
The general form of a pointer variable declaration is:
Syntax:
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name
of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you
use for multiplication. However, in this statement the asterisk is being used to designate a
variable as a pointer. Following are the valid pointer declaration
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character

The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory address. The only
difference between pointers of different data types is the data type of the variable or constant that
the pointer points to.
Using Pointers in C++:
There are few important operations, which we will do with the pointers very
frequently. (a) we define a pointer variables (b) assign the address of a variable to a pointer
and (c) finally access the value at the address available in the pointer variable. This is done by
using unary operator * that returns the value of the variable located at the address specified by
its operand. Following example makes use of these operations:

#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable

Page 31
EE T46 Data Structures and Object Oriented Programming

cout << "Value of var variable: ";


cout << var << endl;

// print the address stored in ip pointer variable


cout << "Address stored in ip variable: ";
cout << ip << endl;

// access the value at the address available in pointer


cout << "Value of *ip variable: ";
cout << *ip << endl;

return 0;
}

When the above code is compiled and executed, it produces result something as follows:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

Various concepts in pointer are:


 Null pointer
 Pointer arithmetic
 Array of pointer
 Pointer to pointer
 Passing pointer as an agrument to function
 Pointer to function

C++ Null pointer:


It is always a good practice to assign the pointer NULL to a pointer variable in case you
do not have exact address to be assigned. This is done at the time of variable declaration. A
pointer that is assigned NULL is called a null pointer. The NULL pointer is a constant with a
value of zero defined in several standard libraries, including iostream. Consider the following
program:
#include <iostream>
using namespace std;
int main ()
{
int *ptr = NULL;
cout << "The value of ptr is " << ptr ;
return 0;
}
When the above code is compiled and executed, it produces the following result:
The value of ptr is 0

On most of the operating systems, programs are not permitted to access memory at
address 0 because that memory is reserved by the operating system. However, the memory
address 0 has special significance; it signals that the pointer is not intended to point to an
accessible memory location. But by convention, if a pointer contains the null (zero) value, it is
assumed to point to nothing.

Page 32
EE T46 Data Structures and Object Oriented Programming

C++ pointer arithmetic


As you understood pointer is an address which is a numeric value; therefore, you can
perform arithmetic operations on a pointer just as you can a numeric value. There are four
arithmetic operators that can be used on pointers: ++, --, +, and -. To understand pointer
arithmetic, let us consider that ptr is an integer pointer which points to the address 1000.
Assuming 32-bit integers, let us perform the following arithmatic operation on the pointer:
ptr++
the ptr will point to the location 1004 because each time ptr is incremented, it will point
to the next integer. This operation will move the pointer to next memory location without
impacting actual value at the memory location. If ptr points to a character whose address is
1000, then above operation will point to the location 1001 because next character will be
available at 1001.

Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the variable pointer can
be incremented, unlike the array name which cannot be incremented because it is a constant
pointer. The following program increments the variable pointer to access each succeeding
element of the array:

#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have array address in pointer.
ptr = var;
for (int i = 0; i < MAX; i++) {
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// point to the next location
ptr++;
}

return 0;
}

When the above code is compiled and executed, it produces result something as follows:

Address of var[0] = 0xbfa088b0


Value of var[0] = 10
Address of var[1] = 0xbfa088b4
Value of var[1] = 100
Address of var[2] = 0xbfa088b8
Value of var[2] = 200

Page 33
EE T46 Data Structures and Object Oriented Programming

Decrementing a Pointer:
The same considerations apply to decrementing a pointer, which decreases its value by
the number of bytes of its data type as shown below:

#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have address of the last element in pointer.
ptr = &var[MAX-1];
for (int i = MAX; i > 0; i--) {
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// point to the previous location
ptr--;
}
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Address of var[3] = 0xbfdb70f8
Value of var[3] = 200
Address of var[2] = 0xbfdb70f4
Value of var[2] = 100
Address of var[1] = 0xbfdb70f0
Value of var[1] = 10

Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and
p2 point to variables that are related to each other, such as elements of the same array, then p1
and p2 can be meaningfully compared. The following program modifies the previous example
one by incrementing the variable pointer so long as the address to which it points is either less
than or equal to the address of the last element of the array, which is &var[MAX - 1]:

#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have address of the first element in pointer.
ptr = var;
int i = 0;
while ( ptr <= &var[MAX - 1] )
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;

Page 34
EE T46 Data Structures and Object Oriented Programming

cout << "Value of var[" << i << "] = ";


cout << *ptr << endl;
// point to the previous location
ptr++;
i++;
}
return 0;
}
When the above code is compiled and executed, it produces result something as follows:

Address of var[0] = 0xbfce42d0


Value of var[0] = 10
Address of var[1] = 0xbfce42d4
Value of var[1] = 100
Address of var[2] = 0xbfce42d8
Value of var[2] = 200

C++ array of pointers


There may be a situation, when we want to maintain an array, which can store pointers to an int
or char or any other data type available. Following is the declaration of an array of pointers to
an integer:

int *ptr[MAX];
This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a
pointer to an int value. Following example makes use of three integers which will be stored in
an array of pointers as follows:

#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr[MAX];

for (int i = 0; i < MAX; i++) {


ptr[i] = &var[i]; // assign the address of integer.
}

for (int i = 0; i < MAX; i++) {


cout << "Value of var[" << i << "] = ";
cout << *ptr[i] << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

Page 35
EE T46 Data Structures and Object Oriented Programming

You can also use an array of pointers to character to store a list of strings as follows:

#include <iostream>
using namespace std;
const int MAX = 4;
int main ()
{
char *names[MAX] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali",
};
for (int i = 0; i < MAX; i++) {
cout << "Value of names[" << i << "] = ";
cout << names[i] << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali

C++ Pointer to Pointer (Multiple Indirection)


A pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a
pointer contains the address of a variable. When we define a pointer to a pointer, the first
pointer contains the address of the second pointer, which points to the location that contains
the actual value as shown below.

A variable that is a pointer to a pointer must be declared as such. This is done by placing
an additional asterisk in front of its name. For example, following is the declaration to declare a
pointer to a pointer of type int:
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that
value requires that the asterisk operator be applied twice, as is shown below in the example:

#include <iostream>
using namespace std;
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
// take the address of var
ptr = &var;
Page 36
EE T46 Data Structures and Object Oriented Programming

// take the address of ptr using address of operator &


pptr = &ptr;
// take the value using pptr
cout << "Value of var :" << var << endl;
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of var :3000
Value available at *ptr :3000
Value available at **pptr :3000

Passing pointers to functions in C++


C++ allows you to pass a pointer to a function. To do so, simply declare the function
parameter as a pointer type. Following a simple example where we pass an unsigned long
pointer to a function and change the value inside the function which reflects back in the calling
function:

#include <iostream>
using namespace std;
// function declaration:
double getAverage(int *arr, int size);
int main ()
{
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
// output the returned value
cout << "Average value is: " << avg << endl;
return 0;
}

double getAverage(int *arr, int size)


{
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = double(sum) / size;
return avg;
}
When the above code is compiled together and executed, it produces the following result:
Average value is: 214.4

Page 37
EE T46 Data Structures and Object Oriented Programming

Pointer to function:
#include <iostream>
using namespace std;
float average(float x,float y,float z)
{
return (x+y+z)/3;
}
int main()
{
float a=10,b=20,c=50;
float avg;
float (*p)(float,float,float);
p=&average;
avg=(*p)(a,b,c);
cout<<avg;
}

Page 38

You might also like