Unit5 Inheritance
Unit5 Inheritance
Sahara Campus
BSc CSIT – Second Semester
Compiled By:
1
Compiled By:
ER. Sachin Oli
Introduction to Inheritance
The mechanism of deriving a new class from an old class is called
inheritance.
It provides the use of reusability.
C++ class es can be re-used using inheritance
The derived class inherites the some of or all of the properties of
the base class .
A derived class with only one base class is called single inheritance.
A class can inherit properties from more than one class which is known
as multiple
inheritance.
A class can be derived from another derived class which is known as
multilevel inheritance.
When the properties of one class are inherited by more than one class,
it is called hierarchical
inheritance.
A A B
A
B C C
Fig. Fig. Fig.
Single inheritance Multiple inheritance Multilevel Inheritance
2
Compiled By:
ER. Sachin Oli
A A
B C D B C
Fig. Hierarchical
Amrit Campus
D
Fig. Forms of Inheritance
Example:
class ABC: private xyz // private derivation
{
Member of ABC
};
class ABC: public xyz // public derivation
{
Members of ABC
};
class ABC: xyz // private derivation by default
{
Members of ABC
};
Single Inheritance:
a. public derivation
#include<iostream>
3
Compiled By:
ER. Sachin Oli
Amrit Campus
public:
void mul(void);
void display(void);
};
//……………………
void B:: get_ab(void)
{
a = 5; b = 10;
}
int B:: get_a()
{
return a;
}
void B:: show_a()
{
cout<<"a="<<a<<"\n";
}
void D:: mul()
{
c = b * get_a(); // a is private can not be inherited
}
void D:: display()
{
cout<<"a="<<get_a()<<"\n";
cout<<"b="<<b<<"\n";
cout<<"c="<<c<<"\n";
}
int main()
{
4
Compiled By:
ER. Sachin Oli
OUTPUT
D d;
a=5
d.get_ab();
a=5
[Link](); b =10
d.show_a(); c= 50
[Link]();
return 0;
}
Amrit Campus
int b;
void get_ab();
int get_a(void);
void show_a(void);
};
class D: private B
{
int c;
public:
void mul (void);
void display (void);
};
// ……………………….
void B:: get_ab(void) OUTPUT
{
cout<<” Enter value for a and b”; Enter values for a and
b: 5 10
cin>> a >>b; a=5
} b = 10
int B:: get_a() c = 50
{
5
Compiled By:
ER. Sachin Oli
return a;
}
void B:: show_a ()
{
cout <<”a = “ << a <<”\n”;
}
void D:: mul ()
{
get_ab();
c =b * get_a(); // a is private
}
void D:: display()
{ show_a();
cout<<”b=”<<”\n”;
cout<<”c=”<<c<<”\n”;
}
int main()
{ D d;
// d.get_ab(); won’t work
[Link]();
// show_a(); won’t work
[Link]();
//d.b = 20; won’t work b is private
Amrit Campus
return 0;
}
Making a private member inheritable:
It is seen that a private member of base class cannot be inherited and
therefore it is not available
for the derived class directly. If the private data needs to be
inherited by a derived class , this can
be accomplished by modifying the visibility limit of the “private”
member by making it “public”.
But this would make is accessible to all the other functions of the
program, thus taking away the
advantage of data hiding. For this, C++ provides a third visibility
modifier “protected”, which
serve a limited purpose in inheritance. Thus, a member declared as
“protected” is accessible by
the member functions within its class and any class immediately derived
from it.
Visibility of inherited members:
Derived class visibility
Base class
6
Compiled By:
ER. Sachin Oli
Public Private
Protected
Visibility
derivation derivation
derivation
Private Not inherited Not inherited Not
inherited
Protected Protected Private
Protected
Public Public Private
Protected
Multilevel Inheritance:
class A { ……………..}; // base class
class B: public A { ………….. }; // B derived from A
class C: public B { …………… }; // C derived from B
A Grand father
B Father
C Child
# include <iostream>
using namespace std;
class student
{
protected:
int roll_number;
public:
void get_number (int);
void put_number (void);
};
Amrit Campus
roll_number = a;
}
void student:: put_number()
{
cout << “roll number:” << roll_number <<”\n”;
7
Compiled By:
ER. Sachin Oli
Amrit Campus
student1.get_number (111);
student1.get_marks (75.0, 59.5);
8
Compiled By:
ER. Sachin Oli
[Link]();
}
output:
Roll number: 111
Marks in sub1 = 75
Marks in sub2 = 59.5
Total = 134.5
Multiple Inheritance:
Eg.
# include <iostream>
using namespace std;
class M
{
protected:
Int m;
public:
void get_m (int);
};
class N
{
Amrit Campus
9
Compiled By:
ER. Sachin Oli
protected:
int n;
public:
void get_n(int);
};
class P: public M, public N
{
public:
void display (void);
};
void M:: get_m(int x)
{
m = x;
}
void N:: get_n(int y)
{
n=y;
}
void p:: display(void)
{
cout <<”m=”<<m<<”\n”;
cout <<”n=””<<n<<”\n”;
cout <<”m*n=” << m*n << “\n”;
}
int main ()
{
P p;
p.get_m(10);
p.get_n(20);
[Link]();
return 0;
}
Ambiguity Resolution in inheritance:
If same function name occurs is base and derived class, then ambiguity
arises. To avoid this
problem, we use scope resolution operator with the function.
Eg:
class M
{
public:
void display (void)
{
cout<<” class M\n”;
}
10
Compiled By:
ER. Sachin Oli
Amrit Campus
};
class N
{
public:
void display (void)
{
cout <<”class N\n”;
}
};
class P: public M, public N
{
public:
void display(void) // overrides display () of M and N
{
M:: display ();
}
};
int main ()
{
P p;
[Link]();
return 0;
}
Output:
class M
Hybrid Inheritance:
class sports Student
{
protected:
float score;
Sports
public: test
void get_score(float);
void put_score (void)
};
class result: public test, public sports result
{
……………….
……………….
……………….
11
Compiled By:
ER. Sachin Oli
};
class test: public student
{
Amrit Campus
……………….
……………….
……………….
};
Constructors in derived classes:
As long as no base class constructors takes any arguments, the derived
class need not
have a constructor function.
If any base class contains a constructor with one or more arguments,
then it is
mandatory for the derived class to have constructor and pass the
arguments to the base
class constructors.
When both the derived and base classes contain constructors, the base
constructor is
executed first and then the constructor in the derived class is
executed.
In case of multiple inheritance, the base class are constructed “in
the order in which
they appear in the declaration of the derived class.” Similarly, in a
multilevel inheritance,
the constructors will be executed in the order of inheritance.
Execution of base class constructor
Method of inheritance Order of execution
class B: public A A (); base constructor
{ B (); derived constructor
};
class A: public B, public C B (); base (first)
{ C(); base (second)
}; A (); derived
class A: public B, virtual public C(); virtual base
C B(); ordinary base
A(); derived
Example
# include <iostream>
using namespace std;
class alpha
{
12
Compiled By:
ER. Sachin Oli
int x;
public:
alpha (int i)
{
x = i;
cout <<"alpha initialized \n";
}
void show_x(void)
Amrit Campus
{
cout<<"x = "<< x <<"\n";
}
};
class beta
{
float y;
public:
beta (float j)
{
y = j;
cout<<"beta initialized\n";
}
void show_y (void)
{
cout <<"y="<<y <<"\n";
}
};
class gamma: public beta, public alpha // order of execution
{
int m,n;
public:
gamma (int a, float b, int c, int d): alpha (a), beta (b)
{
m = c;
n = d;
cout<<"gamma initialized\n";
}
void show_mn(void)
{
cout<<"m="<<m<<"\n"
<<"n = " << n <<"\n";
}
};
13
Compiled By:
ER. Sachin Oli
int main ()
{
gamma g(5, 10.75, 20, 30);
g.show_x();
g.show_y();
g.show_mn();
Amrit Campus
Output:
beta initialized
alpha initialized
gamma initialized
x=5
y = 10.75
m = 20
n = 30
Note: Beta is initialized first, although it appears second in the derived constructor. This
is because it has been declared first in the derived class header
line. Also, alpha (a)
and beta (b) are function calls.
Destructor in derived class
Example1
#include<iostream>
using namespace std;
class baseClass
14
Compiled By:
ER. Sachin Oli
{
public:
baseClass()
{
cout << "I am baseClass constructor" << endl;
}
~baseClass()
{
cout << "I am baseClass destructor" << endl;
}
};
Amrit Campus
~derivedClass()
{
cout <<" I am derivedClass destructor" << endl;
}
};
int main()
{
derivedClass D;
return 0;
}
Output
Example 2
#include <iostream>
using namespace std;
class alpha
{
int x;
15
Compiled By:
ER. Sachin Oli
public:
alpha (int i)
{
x = i;
cout <<"alpha initialized \n";
}
void show_x(void)
{
cout<<"x = "<< x <<"\n";
}
~alpha ()
{
Amrit Campus
};
class beta
{
float y;
public:
beta (float j)
{
y = j;
cout<<"beta initialized\n";
}
void show_y (void)
{
cout <<"y="<<y <<"\n";
}
~beta ()
{
cout<<"\n----------beta destroyed--------------";
}
};
class gamma: public beta, public alpha // order of execution
{
int m,n;
16
Compiled By:
ER. Sachin Oli
public:
gamma (int a, float b, int c, int d): alpha (a), beta (b)
{
m = c;
n = d;
cout<<"gamma initialized\n";
}
void show_mn(void)
{
cout<<"m="<<m<<"\n"
<<"n = " << n <<"\n";
}
~gamma ()
{
cout<<"\n-----------gamma destroyed-------------------";
}
};
Amrit Campus
int main ()
{
gamma g(5, 10.75, 20, 30);
g.show_x();
g.show_y();
g.show_mn();
}
Destructor in Multiple Inheritance
#include<iostream>
using namespace std;
class baseClass1 {
public:
baseClass1() {
cout<<"I am baseClass1 constructor"<<endl;
}
~baseClass1()
{
cout<<"I am baseClass1 destructor"<<endl;
}
};
17
Compiled By:
ER. Sachin Oli
class baseClass2 {
public:
baseClass2() {
cout<<"I am baseClass2 constructor"<<endl;
}
~baseClass2() {
cout<<"I am baseClass2 destructor"<<endl;
}
};
~derivedClass() {
cout<<"I am derivedClass destructor"<<endl;
}
};
Amrit Campus
int main() {
derivedClass D;
return 0;
}
Output
18
Compiled By:
ER. Sachin Oli
}
All objects of gamma class will contain the objects a and b. this kind
of relationship is
called containership or nesting.
A class contain object of another class. This is known as
containership or nesting.
Example
#include<iostream>
#include<conio.h>
const int len=20;
using namespace std;
class student
{
private:
char school[len];
char degree[len];
public:
void getdata()
{
cout<<"Enter name of the school or university:";
Amrit Campus
cin>>school;
cout<<"Enter highest degree earned:";
cin>>degree;
}
void putdata()
{
cout<<endl<<"School or university:"<<school<<endl;
cout<<endl<<"Highest degree earned:"<<degree<<endl;
}
};
class employee
{
private:
char name[len];
unsigned long number;
public:
void getdata()
{
cout<<"Enter name of employee:";
cin>>name;
cout<<"Enter number:";
19
Compiled By:
ER. Sachin Oli
cin>>number;
}
void putdata()
{
cout<<endl<<"Name:"<<name;
cout<<endl<<"Number:"<<number<<endl;
}
};
class manager
{
private:
char title[len];
double dues;
employee emp;
student stu;
public:
void getdata()
{
[Link]();
cout<<"Enter title:";cin>>title;
cout<<"Enter golf club dues:";cin>>dues;
[Link]();
}
void putdata()
Amrit Campus
{
[Link]();
cout<<"Title:"<<title;
cout<<"Gulf club dues:"<<dues;
[Link]();
}
};
int main()
{
manager m;
[Link]();
[Link]();
getch();
return 0;
}
20
Compiled By:
ER. Sachin Oli
Example
#include <iostream>
#include<string.h>
class Address {
public:
char add[30];
Address(char a[])
strcpy(add,a);
Amrit Campus
};
class Employee
21
Compiled By:
ER. Sachin Oli
private:
public:
int id;
char name[20];
{ id=i;
strcpy(name,j);
address=add;
void display()
cout<<"address="<< address->add;
};
int main(void) {
char a[]="kathmandu";
char b[]="Haribol";
Employee e1 = Employee(501,b,&a1);
22
Compiled By:
ER. Sachin Oli
[Link]();
return 0;
Amrit Campus
Output:
Polymorphism:
Polymorphism is one of the crucial features of OOP.
It simply means, one name, multiple forms.
Polymorphism is implemented using the overloaded functions and operators
23
Compiled By:
ER. Sachin Oli
.
Polymorphism
Virtual Functions:
When we use the same functions name in both the base and derived classes, the function in
base
class is declared as virtual using the key word “virtual” preceding its
normal declarations.
Example
#include<iostream>
using namespace std;
class Base
{
public:
void display ()
{
cout<<"\ndisplay base:";
}
virtual void show()
{
cout <<"\nshow base\n";
24
Compiled By:
ER. Sachin Oli
}
};
class Derived: public Base
{
public:
void display ()
{
cout<<"\n\ndisplay derived:";
}
void show ()
{
cout<<"\nshow derived\n";
}
};
int main()
{
Base B;
Derived D;
Base *bptr;
cout<<"\nbptr point to base\n";
bptr = &B;
bptr->display(); //calls base version
bptr->show(); //calls base version
cout<<"\nbptr points to derived\n";
bptr = &D;
bptr->display(); // calls base version
bptr->show();//calls derived version
}
Output:
Note:
When bptr is made to point to the object ‘D’ the statement
bptr display ();
calls only the function associated with the base (i.e Base::display();), whereas the statement
bptr show ();
calls the derived version of show(). This is because the function “display ()” has not been
made
virtual in the base class .
25
Compiled By:
ER. Sachin Oli
};
26
Compiled By:
ER. Sachin Oli
};
int main()
{
Base B;
Derived1 D;
Derived2 E;
Base *bptr;
bptr = &D;
bptr->display();
bptr->show();
return 0;
}
“this” pointer:
C++ uses a unique keyword called “this” to represent an object that invokes a member
function.
“this” is a pointer that points to the object for which “this” function was called. For example,
the
function call [Link] () will set the pointer “this” to the address of the object A.
Eg:
class ABC
{
int a;
………….
27
Compiled By:
ER. Sachin Oli
………….
………….
};
The private variable a can be used directly inside a member function like
a = 123;
We can also use the following statement to do the same job.
this a = 123;
Example 1
# include<iostream>
using namespace std;
class X
{
int a;
public:
void input (int a)
{
this a = a;
}
void output ()
{
cout <<a;
}
};
int main ()
{
X ob;
[Link](2);
[Link]();
return();
}
Example 2:
# include<iostream>
using namespace std;
28
Compiled By:
ER. Sachin Oli
class X
{
int a,b;
public:
void input ()
{
this a = 10;
this b = 11;
}
void output ()
{
cout<<a<<” “<<b;
}
};
int main ()
{
X ob;
[Link] ();
[Link] ();
return 0;
}
Example 3:
#include<iostream>
#include<string.h>
using namespace std;
class person
{
char name[20];
float age;
public:
person(char s[],float a)
{
strcpy(name,s);
age=a;
}
29
Compiled By:
ER. Sachin Oli
if([Link]>=age)
return x;
else
return *this;
}
void display(void)
{
cout<<"Name:"<<name<<"\n"<<"Age:"<<age<<"\n";
}
};
int main()
{ char name1[10]="John";
char name2[10]="Jack";
char name3[10]= "Jim";
person P1(name1,37.50),P2(name2,29.0),P3(name3,40.25);
person P=[Link](P3);
P=[Link](P2);
30
Compiled By:
ER. Sachin Oli
Grand parent
Parent 1 Parent 2
Child
Here, inheritance by the “child” might pose some problems. All the public and protected
members of “grand parent” are inherited into child twice, first via “parent1” and again via
“parent2”.
This means, ‘child’ would have duplicate sets of the members inherited from grand parent.
This
introduces ambiguity and should be avoided.
The duplication of inherited members due to these multiple paths can be avoided by making
the
common base class as virtual base class .
Eg:
class A // grand parent
{
………………
………………
};
class B1: virtual public A // parent 1
{
………………
………………
};
class B2: public virtual // parent 2
{
………………
31
Compiled By:
ER. Sachin Oli
Amrit Campus
………………
};
class C: public B1, public B2 //child
{
………………
……………… // only one copy of a will be inherited.
};
Student
Test Sports
Results
#include<iostream>
using namespace std;
class student
{
protected:
int roll_number;
public:
void get_number(int a)
{
roll_number = a;
}
void put_number(void)
{
cout<<"Roll No:"<<roll_number<<"\n";
}
};
class test: virtual public student
{
protected:
float part1, part2;
public:
void get_marks (float x, float y)
32
Compiled By:
ER. Sachin Oli
{
part1 = x; part2 = y;
}
void put_marks(void)
{
cout <<"Marks obtained:"<<"\n"
<<"part1 = "<<part1<<"\n"
<<"part2 ="<<part2<<"\n";
}
};
33
Compiled By:
ER. Sachin Oli
student1.get_number (678);
student1.get_marks(30.5, 25.5);
student1.get_score(7.0);
[Link]();
}
Such function are called pure virtual function. A pure virtual function
is a function declared in a
base class that has no definition relative to the base class .
A class containing pure virtual functions cannot be used to declare any
objects of its own.
Eg:
class media
{
protected:
Char title [50];
float price;
public:
…………………
…………………
…………………
virtual void display () {} //empty virtual function
};
34
Compiled By:
ER. Sachin Oli
Amrit Campus
#include<iostream>
#include<string.h>
using namespace std;
class Person
{
protected:
char name[20];
int code;
public:
Person(){}
Person(char x[], int c)
{
strcpy(name,x);
code=c;
}
void showname()
{
cout<<"\nName of aperson is: "<<name;
cout<<"\nHis code is: "<<code;
}
};
class Account:public virtual Person
{
protected:
float pay;
public:
Account(float p)
{ pay=p; }
void showacc()
{
cout<<"\nPayment Given to him is: " <<pay;
}
};
class Admin:public virtual Person
{
protected:
35
Compiled By:
ER. Sachin Oli
float experience;
public:
Admin(float a)
{ experience=a; }
};
class Master:public Account, public Admin
{
public:
Master(char x[],int c,float p, float e): Person(x,c),
Account(p),Admin(e) // These are function calls
{ }
void show()
{
showname();
showacc();
cout<<"\nHis years of Experience is: "<<experience;
}
};
int main()
{
Master m("Rohit Sharma",1011,50000,5.4);
[Link]();
return 0;
}
Abstract classes:
An abstract class is one that is not used to create objects.
An abstract class is designed only to act as base class (to be
inherited by other
classes).
It is a design concept in program development and provides a base upon
which other
classes may be built.
Student
test Sport
Result 13
36
Compiled By:
ER. Sachin Oli
return 0;
}
Output:
show method is implemented here.
37
Compiled By:
ER. Sachin Oli
class Abstract {
private:
string info;
public:
virtual void printContent() = 0;
};
class Concrete {
private:
string info;
public:
Concrete(string s){
info = s;
}
void display() {
cout << "Concrete Object Information\n" << info << endl;
}
};
int main()
{
/*
* Abstract a;
* Error : Abstract Instance Creation Failed
*/
string s;
s = "This is concrete class";
Concrete c(s);
c. display();
return 0;
}
Overriding:
In inheritance relationship, a base class method is said to be
overridden if a method is defined in
child class with same type, signature and name.
Eg:
#include<iostream>
using namespace std;
class A
{
public:
38
Compiled By:
ER. Sachin Oli
void show()
{
cout<<"\nbase class show";
}
};
class B: public A
{ public:
void show () //this method overridden base class method
{
cout<<"\nchild class show";
}
};
int main ()
{
B objB;
[Link](); // show child class show
objB.A :: show(); // shows base class show
}
Friend Function
We know that the private member cannot be accessed from outside the class. That is,
a non-
member-function cannot have an access to private data of a class. However, there could
be a
situation where we would like two classes to share a particular function. In such
situation C++
allows the common function to be made friendly with both the classes, thereby
allowing the
function to have access to the private data of these classes. Such a function need not to
be a
member of any of these classes.
To make outside function “friendly” to a class, we have to simply declare this
function as a friend
of the class as shown below :
Class ABC
39
Compiled By:
ER. Sachin Oli
………..
…………
public:
……………
…………..
};
The functions that are declared with the keyword friend are known as friend
functions.
A function can be declared as friend in any number of classes.
A friend function, although not a member function, has full access rights to the
private members
of the class.
40
Compiled By:
ER. Sachin Oli
Example:
#include<iostream>
using namespace std;
class sample
{
int a;
int b;
public:
void setvalue( ) { a=25;b=40;}
friend float mean( sample s);
};
float mean (sample s)
{
return (float(s.a+s.b)/2.0);
}
int main ( )
{
sample x;
x . setvalue( );
cout<<"mean value="<<mean(x)<<endl;
return(0);
}
Member functions of one class can be friend function of another class.
In such cases, they are defined
using the scope resolution operator.
E.g.
class X
{ ………..
………..
………..
};
41
Compiled By:
ER. Sachin Oli
class Y
{ …………..
……………
};
#include<iostream>
class abc;
class xyz
int x;
public:
void setvalue(int i) { x= i; }
};
class abc
42
Compiled By:
ER. Sachin Oli
int a;
public:
};
cout<<m.x;
else
cout<< n.a;
int main( )
abc j;
j . setvalue( 10);
xyz s;
43
Compiled By:
ER. Sachin Oli
[Link](20);
max( s , j );
return(0);
#include<iostream>
using namespace std;
class E2;
class E3;
class E1
{ char name[10];
float salary;
public:
void set()
{
cout<<"\n Enter first Employee name and salary";
cin>>name>>salary;
}
friend void process(E1,E2,E3);
};
class E2
{
char name[10];
float salary;
public:
void set()
{
cout<<"\n Enter second Employee name and salary";
cin>>name>>salary;
}
friend void process(E1,E2,E3);
44
Compiled By:
ER. Sachin Oli
};
class E3
{
char name[10];
float salary;
public:
void set()
{
cout<<"\n Enter third Employee name and salary";
cin>>name>>salary;
}
friend void process(E1,E2,E3);
};
void process(E1 x, E2 y, E3 z)
{
cout<<"\n\nFirst Employee name= "<< [Link];
cout<<"\nFirst Employee salary= "<<[Link];
int main()
{
E1 A;
E2 B;
E3 C;
[Link]();
[Link]();
[Link]();
process(A,B,C);
return 0;
}
Output:
45
Compiled By:
ER. Sachin Oli
A static function can be called using the class-name (instead of its objects) as follows:
Class-name : : function-name
Example:
#include<iostream>
using namespace std;
class test
{
int code;
static int count; // static member variable
public:
void setcode(void)
{
code=++count;
}
void showcode(void)
{
cout<<"object member : "<<code<<endl;
}
static void showcount(void)
{ cout<<"count="<<count<<endl;
//cout<<code; //this can not be done here because static function will
access only static variables
}
};
int main()
{
46
Compiled By:
ER. Sachin Oli
test t1,t2;
[Link]( );
[Link]( );
test :: showcount ( );
test t3;
[Link]( );
test:: showcount( );//accessing static member function
[Link]( );
[Link]( );
[Link]( );
//test t4;
//[Link](); //it can also be done
return(0);
}
Output
Virtual Destructor
Deleting a derived class object using a pointer of base class type that
has a non-virtual destructor results
in undefined behavior. To correct this situation, the base class should
be defined with a virtual
destructor. For example, following program results in undefined behavior
#include <iostream>
using namespace std;
class base {
public:
base()
{ cout << "Constructing base\n"; }
~base()
{ cout<< "Destructing base\n"; }
47
Compiled By:
ER. Sachin Oli
};
int main()
{
derived *d = new derived();
base *b = d;
delete b;
getchar();
return 0;
}
Output
#include <iostream>
using namespace std;
class base {
public:
base()
{ cout << "Constructing base\n"; }
virtual ~base()
{ cout << "Destructing base\n"; }
};
48
Compiled By:
ER. Sachin Oli
int main()
{
derived *d = new derived();
base *b = d;
delete b;
getchar();
return 0;
}
Output
49
Compiled By:
ER. Sachin Oli
template<class T>
class class_name
{
………………. //class member
………………. // specifications with
………………. // anonymous type T
………………. // where or appropriate
};
Example:
#include <iostream>
using namespace std;
template<class T1>
class Test
{
T1 a;
public:
void add (T1 x, T1 y)
{
a=x+y;
}
void mul(T1 x, T1 y)
{
a = x * y;
}
void div(T1 x, T1 y)
{
a = x/y;
}
void sub(T1 x, T1 y)
{
a = x -y;
}
void show()
{
cout<<a<<"\n";
}
};
int main()
{
Test <float> testf;
Test <int> testi;
50
Compiled By:
ER. Sachin Oli
[Link](5.23,6.43);[Link]();
[Link](6.4,2.0);[Link]();
[Link](20,32); [Link]();
[Link](200,150); [Link]();
return 0;
}
Output
}
};
int main()
{
Test<float, int> test1(1.23,123);
Test<int,char>test2(100,'W');
51
Compiled By:
ER. Sachin Oli
[Link]();
[Link]();
return 0;
}
Output
Function Templates:
template<class T>
returntype functionname (arguments of type t)
{
……………………..
…………………….. // Body of function with type T
……………………..
…………………….. // Wherever appropriate
}
#include <iostream>
using namespace std;
52
Compiled By:
ER. Sachin Oli
int main()
{
fun(100,200,11.22,33.44);
return 0;
}
#include<iostream>
#include<string.h>
using namespace std;
template<class T1, class T2>
void display (T1 x, T2 y)
{
cout<< x << " " <<y <<"\n";
}
int main ()
{
display (2022, "NEPAL");
display (12.34, 1234);
return 0;
}
53
Compiled By:
ER. Sachin Oli
Example:
#include<iostream>
#include<string.h>
using namespace std;
template<class T>
void display (T x)
{
cout<<”Template display:”<<x<<”\n”;
}
void display (int x)
{
cout<<”Explicity display:”<<x<<”\n”;
}
int main()
{
display (100);
display(12.34);
display (‘C’);
return 0;
}
54
Compiled By:
ER. Sachin Oli
};
template <class T1>
class polar
{
T1 radius;
T1 thita;
public:
polar(){ }
polar(rectangle <float> r)
{ T1 tempx=r.get_x();
T1 tempy=r.get_y();
radius = sqrt(tempx*tempx + tempy*tempy);
thita = atan(tempy/tempx);
}
void show()
{ cout<<"radius is:"<<radius<<endl;
cout<<"thita is:"<<thita*(180/3.14);
}
};
int main()
{
rectangle <float> r(6.0,9.0);
polar <float> p(r);
[Link]();
return 0;
}
Exception Handling
The two most common types of bugs are logic errors and syntactic errors
The logic errors occur due to poor understanding of the problem and solution
procedure
The syntactic error occurs due to poor understanding of the language itself
We often come across with some peculiar problems other than logic or syntax errors.
They are
known as exceptions.
55
Compiled By:
ER. Sachin Oli
The purpose of exception handling mechanism is to provide means to detect and report an
“exceptional Circumstances” so that appropriate actions can be taken.
Note: The catch block that catches the exceptions must immediately follow the try block that
throws the
exception.
General form:
56
Compiled By:
ER. Sachin Oli
Amrit Campus
--------------
--------------
try {
---------
---------
----------
----------
----------
---------
----------
Example
57
Compiled By:
ER. Sachin Oli
#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Enter values of a and b\n";
cin>>a>>b;
int x = a - b;
try{
if(x!=0)
{
cout<<"Result(a/x)="<<a/x<<"\n";
}
else{
throw(x);
}
}
catch(int i)
{
cout<<"Exception caught : x= "<<x<<"\n";
}
cout<<"END" ;
return 0;
}
58
Compiled By:
ER. Sachin Oli
Amrit Campus
…….
}
try
{
…..
….. invoke function here
…..
}
catch (type arg) // catches exception
{
…….
……. Handles exception here
…….
Note: The try block is immediately followed by the catch block, irrespective of the location of
the throw
point. In the below program show how a try block invokes a function that generates an
exception
/* Throw point outside the try block */
#include <iostream>
using namespace std;
void divide(int x, int y, int z)
{
cout << "\n we are inside the function \n";
if((x-y)!=0) // it is ok
{
int r=z/(x-y);
cout << "Result= " << r <<"\n";
}
59
Compiled By:
ER. Sachin Oli
int main()
{
try
{
}
}
Example:
#include<iostream>
void test(int x)
try
60
Compiled By:
ER. Sachin Oli
else
else
catch(char c) // catch 1
catch(int m) // catch 2
catch(double d) // catch 3
61
Compiled By:
ER. Sachin Oli
int main()
test(1);
test(0);
test(-1);
test(2);
62
Compiled By:
ER. Sachin Oli
#include <iostream>
using namespace std;
void test(int x)
{
try
{
if (x==0) throw x;
if (x==-1) throw 'x';
if (x==1) throw 1.0;
}
catch (...)
{
cout << "Caught an exception \n";
}
}
int main()
{
cout << "Testing generic catch \n";
test(-1);
test(0);
test(1);
return 0;
}
Rethrowing an Exception
#include <iostream>
using namespace std;
void divide(double x, double y)
{
cout << "Inside function \n";
try
{
if (y==0.0)
throw y; // throwing double
else
cout << "Division=" << x/y << "\n";
}
catch (double)
63
Compiled By:
ER. Sachin Oli
// catch a double
{
cout << "caught double inside function \n";
throw ; // re-throwing double
}
cout << "End of function \n \n";
}
int main()
{
cout << "Inside main \n";
try
{
divide(10.5,2.0);
divide(20.0,0.0);
}
catch (double)
{
cout << "Caught double inside main \n";
}
cout << "End of main \n";
return 0;
}
Amrit Campus
All programs require some input and produce some output but those input and output are lost
as the
program terminates. Files are required to save our data for future use. Programs would not be
very
useful if they cannot store data in files. When data volume is large it is generally not
convenient to enter
the data through console. In case cases data can be stored in a file and then the program can
read the
data from data file rather than from the console.
64
Compiled By:
ER. Sachin Oli
The various operations possible on a data file using C++ programs are:
1. Opening a file
2. Reading data stored in the file
3. Writing/appending data from a program into a data file
4. Saving the data file onto some secondary storage device
5. Closing the data file once the ensuring operations are over
6. Checking status of file operation
Opening a file
The first operation generally done on an object of one of the stream classes is to associate it to
a real
file, that is to say, to open a file. The open file is represented within the program by a stream
object and
any input or output performed on this stream object will be applied to the physical file. A data
file can
be opened in a program in many ways. These methods are described below:
OR
Closing a file
When reading, writing or consulting operations on a file are complete we must close it to so
that it
becomes available again. In order to do that we shall call the member function close (), that is
in charge
of flushing the buffers and closing the file. Its form is quite simple:
Amrit Campus
65
Compiled By:
ER. Sachin Oli
void close()
Once this member function is called, the stream object can be used to open another file and the
file is
available again to be opened by other processes.
Unformatted Input/output
With extraction operator reading terminates after reading white space character therefore
above
program is able to read single word from file. We can overcome above problem by using
getline ()
function as below:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
char str[80];
[Link]("G:\\[Link]");
[Link](str,79);
cout<<"Reading contents From file:\n"<<str<<endl;
return 0;
}
The class ifstream has a member function eof() that returns a nonzero
value if the end of file has been
reached. This value indicates that there are no more characters in the
file to be read further. This
function is therefore used in the while loop for stopping condition. End
of file can be detected in two
ways: Using EOF () member function and using filestream object.
66
Compiled By:
ER. Sachin Oli
#include<iostream>
#include<fstream>
using namespace std;
Amrit Campus
int main()
{
ifstream fin;
char ch;
[Link]("G:\\[Link]");
while(![Link]())
{
[Link](ch);
cout<<ch;
}
return 0;
}
return 0;
}
Amrit Campus
67
Compiled By:
ER. Sachin Oli
Write a program to read the contents of a file and display them on the screen insertion
opereator and
getline method:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
char str[100];
[Link]("G:\\[Link]");
while(![Link]())
{
[Link](str,79);
cout<<str;
}
return 0;
}
Write a program to read the contents of a text file and display them on the screen using
extraction
operator
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
char str[100];
[Link]("G:\\[Link]");
while(![Link]())
{
fin>>str;
cout<<str<<" ";
}
return 0;
}
Amrit Campus
68
Compiled By:
ER. Sachin Oli
Example:
/*-------- Program to write data by using write() member function --------*/
#include<iostream>
#include<fstream>
using namespace std;
class Student
{
public:
int roll;
char name[20];
char address[20];
};
int main()
{
Student s;
ofstream fout;
[Link]("G:\\[Link]");
cout<<"Enter Rollno:"<<endl;
cin>>[Link];
cout<<"Enter Name:"<<endl;
cin>>[Link];
cout<<"Enter Address:"<<endl;
cin>>[Link];
[Link]((char *)&s,sizeof(Student));
[Link]();
cout<<"Writing complete"<<endl;
return 0;
Amrit Campus
69
Compiled By:
ER. Sachin Oli
Program to read data from a binary File using read() member function
#include<iostream>
#include<fstream>
using namespace std;
class Student
{
public:
int roll;
char name[20];
char address[20];
};
int main()
{
Student s;
ifstream fin;
[Link]("G:\\[Link]");
[Link]((char *)&s,sizeof(Student));
cout<<"Rollno:"<<[Link]<<endl;
cout<<"Name:"<<[Link]<<endl;
cout<<"Address:"<<[Link]<<endl;
[Link]();
cout<<"Reading complete"<<endl;
return 0;
}
Amrit Campus
70
Compiled By:
ER. Sachin Oli
{
cout<<"Enter Rollno:"<<endl;
cin>>roll;
cout<<"Enter Name:"<<endl;
cin>>name;
cout<<"Enter Address:"<<endl;
cin>>address;
}
void write_data()
{
};
int main()
{
Student s;
ofstream fout;
[Link]("G:\\[Link]");
for(int i=1;i<=3;i++)
{
cout<<"Enter rollno, name and address of "<<i<<"th
student"<<endl;
s.read_data();
[Link]((char *)&s,sizeof(Student));
}
[Link]();
cout<<"WritÝng complete"<<endl;
return 0;
}
Amrit Campus
#include<iostream>
#include<fstream>
using namespace std;
class Student
{
private:
int roll;
char name[20];
char address[20];
71
Compiled By:
ER. Sachin Oli
public:
void write_data()
{
cout<<roll<<"\t"<<name<<"\
t"<<address<<endl;
}
};
int main()
{
Student s;
ifstream fin;
[Link] ("G:\\[Link]");
cout<<"Rollno\tName\tAddress"<<endl;
Amrit Campus
for(int i=1;i<=3;i++)
{
[Link] ((char *)&s,sizeof(Student));
s.write_data();
}
[Link]();
cout<<"Reading complete"<<endl;
return 0;
}
In some situations, you might want to read some record randomly not sequentially. You can
do this
using two models: One uses an absolute location in the stream called the streampos; the
second woks
like the standard C library functions fseek () for a file and moves a given number of bytes
from the
beginning, current and end part of file.
72
Compiled By:
ER. Sachin Oli
Syntax:
[Link] (no_of_bytes, mode)
[Link] (50,ios::cur)// Moves 50 byes forward from current position
[Link] (50, ios::beg) // Moves 50 bytes forward from current position
Amrit Campus
tellp():- It returns the distance of writing pointer from the beginning in byes
Syntax:
[Link] ()
Example:
long n = [Link] ();
tellg():- It returns the distance of reading pointer from the beginning in bytes.
Syntax:
[Link] ()
Example:
Long n = [Link] ();
Example:
73
Compiled By:
ER. Sachin Oli
};
int main()
{
student s;
int i;
ifstream fin;
[Link]("G:\\[Link]");
Amrit Campus
[Link](sizeof(s)*2,ios::cur);
[Link]((char*)&s,sizeof(student));
[Link]();
[Link]();
return 0;
}
74
Compiled By:
ER. Sachin Oli
char name[20];
char address[20];
void read_data()
{
cout<<"Enter rollno"<<endl;
cin>>rollno;
cout<<"Enter name"<<endl;
cin>>name;
cout<<"Enter address"<<endl;
cin>>address;
}
void display()
{
cout<<rollno<<"\t"<<name<<"\t"<<address<<endl;
}
};
Amrit Campus
int main()
{
Student s;
fstream fin;
int i,r;
[Link]("G:\\[Link]");
cout<<"Reading student information"<<endl;
cout<<"Rollno\tName\tAddress"<<endl;
while([Link]((char *)&s, sizeof(Student)))
{
[Link]();
}
if([Link]())
[Link]();
cout<<"\nEnter the rollno of student whose record is to be
modified"<<endl;
cin>>r;
[Link](sizeof(s)*(r-1));
cout<<"Enter new record"<<endl;
s.read_data();
[Link]((char *)&s,sizeof(Student));
[Link](0);
cout<<"The modified record"<<endl;
while([Link]((char *)&s, sizeof(Student)))
75
Compiled By:
ER. Sachin Oli
{
if(strcmp([Link],"KTM")==0)
[Link]();
}
return 0;
}
Amrit Campus
Amrit Campus
int i;
[Link]("d:\\abc\\[Link]",ios::app);
cout<<"Enter details of "<<N<<"students"<<endl;
for(i=1;i<=N;i++)
{
76
Compiled By:
ER. Sachin Oli
s.read_data();
[Link]((char *)&s,sizeof(Student));
}
int end = [Link]();
int ob = end/sizeof(s);
cout<<"Number of objects = "<<ob;
[Link]();
getch();
return 0;
}
77