0% found this document useful (0 votes)
4 views77 pages

Unit5 Inheritance

This document provides an overview of inheritance in C++ as part of an Object Oriented Programming course. It covers various types of inheritance including single, multiple, multilevel, hierarchical, and hybrid inheritance, along with examples and syntax. Additionally, it discusses visibility modifiers, constructors, destructors, and ambiguity resolution in the context of inheritance.

Uploaded by

Sachin Oli
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views77 pages

Unit5 Inheritance

This document provides an overview of inheritance in C++ as part of an Object Oriented Programming course. It covers various types of inheritance including single, multiple, multilevel, hierarchical, and hybrid inheritance, along with examples and syntax. Additionally, it discusses visibility modifiers, constructors, destructors, and ambiguity resolution in the context of inheritance.

Uploaded by

Sachin Oli
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Compiled By:

ER. Sachin Oli

Sahara Campus
BSc CSIT – Second Semester

Object Oriented Programming in C++

Unit 5: Inheritance [7hrs]

Compiled By:

ER. Sachin Oli

Department of Computer Science & Information Technology

1
Compiled By:
ER. Sachin Oli

Unit 5: Inheritance [7hrs]


Reusability:
Reusability is yet another important feature of OOP. It is always nice if we would reuse
something that already exists rather than trying to create the same thing all over again. It
would
not only save time and money but also reduce frustration and increase reliability. For instance,
the reuse of a class that has already been tested, debugged and used
many times can save us the
effort of developing and testing the same again.
Fortunately, C++ strongly supports the concept of reusability. The C++
classes can be reused in
several ways. Once a class has been written and tested, it can be
adopted by other programmer to
suit their requirements. This is basically done by creating new classes,
reusing the properties of
the existing ones. This mechanism of deriving a new class from an old
one is called inheritance.

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

Defining Derived class :


Syntax:
class derived – class _name:: visibility-mode base-class
{
……………………..
……………………
……………………
// members of derived class
};

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

using namespace std;


class B
{
int a; //private, not inheritable
public:
int b;
void get_ab();
int get_a (void);
void show_a(void);
};
class D: public B // public derivation
{
int c;

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;
}

b. Single inheritance private derivation:


# include <iostream>
using namespace std;
class B
{
int a;
public:

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);
};

void student:: get_number (int a)


{

Amrit Campus

roll_number = a;
}
void student:: put_number()
{
cout << “roll number:” << roll_number <<”\n”;

7
Compiled By:
ER. Sachin Oli

class test: public student // first derivation


{
protected:
float sub1;
float sub2;
public:
void get_marks (float, float);
void put_marks (void);
};

void test:: get_marks (float x, float y)


{
sub1 = x;
sub2 = y;
}
void test:: put_marks ()
{
cout << “marks in sub1 = “<< sub1 <<”\n”;
cout << “marks in sub2 = “<< sub2 <<”\n”;
}
class result: public test // second derivation
{
float total;
public:
void display (void);
};

void result:: display (void)


{
total = sub1 + sub2;
put_number ();
put_marks();
cout << “\n total = “ << total;
}
int main ()
{
result student 1;

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:

B–1 B–2 B–2

In multiple inheritance, a class can inherit the attributes of two or


more class es.

class D: visibility B1, visibility B-2, ………………


{
………………..
………………..
……………….. // body of D
};

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

class C: public A, public B


{
//...
};
1. Here, A class in inherited first, so constructor of class A is called
first then the constructor of class B
will be called next.

2. The destructor of derived class will be called first then destructor


of base class which is mentioned in
the derived class declaration is called from last towards first sequence
wise.

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

class derivedClass: public baseClass


{
public:
derivedClass()
{
cout << "I am derivedClass constructor" << endl;
}

~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 ()
{

cout <<"\n------------alpha destroyed--------------";

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;
}
};

class derivedClass: public baseClass1, public baseClass2 {


public:
derivedClass() {
cout<<"I am derivedClass constructor"<<endl;
}

~derivedClass() {
cout<<"I am derivedClass destructor"<<endl;
}
};

Amrit Campus

int main() {
derivedClass D;
return 0;
}

Output

Member classes: (Nesting of classes):


 Inheritance is the mechanism of deriving certain property of one class
into another
 A member can contain object of other classes as its member as shown
below:
class alpha { …………… };
class beta { ……………. };
class gamma
{
alpha a; // a is an object of class alpha
beta b; // b is a object of class beta

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;
}

Aggregation (HAS-A Relationship)

20
Compiled By:
ER. Sachin Oli

In C++, aggregation is a process in which one class defines another


class as any entity reference. It is
another way to reuse the class. It is a form of association that
represents HAS-A relationship.

Example

Let's see an example of aggregation where Employee class has the


reference
of Address class as data member. In such way, it can reuse the members
of
Address class.

#include <iostream>

#include<string.h>

using namespace std;

class Address {

public:

char add[30];

Address(char a[])

strcpy(add,a);

Amrit Campus

};

class Employee

21
Compiled By:
ER. Sachin Oli

private:

Address* address; //Employee HAS-A Address. Example of


Aggregation

public:

int id;

char name[20];

Employee(int i, char j[], Address* add)

{ id=i;

strcpy(name,j);

address=add;

void display()

{ cout<<id <<" "<<name<< " "<<"\n";

cout<<"address="<< address->add;

};

int main(void) {

char a[]="kathmandu";

char b[]="Haribol";

Address a1= Address(a);

Employee e1 = Employee(501,b,&a1);

22
Compiled By:
ER. Sachin Oli

[Link]();

return 0;

Amrit Campus

Output:

Er. Ranjan Raj Aryal


Amrit Campus

Unit 6: Virtual Function, Polymorphism, and miscellaneous C+


+ Features [5hrs]

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

Compile time & run time polymorphism:


The overloaded member functions are selected for invoking by matching arguments both type
and number. This information is known to the compiler at the compile time and therefore,
compiler is able to select the appropriate function for a particular call at the compile time
itself.
This is called early binding or static binding or static linking. Also known as compile time
polymorphism, early binding simply means that an object is bound to its function call at
compile
time.
It would be better if the appropriate member function could be selected while the program is
running. This is known as run time polymorphism. C++ supports a
mechanism known as virtual
function to achieve run time polymorphism
The selection of the appropriate function for the virtual functions
takes place at run time. In run
time polymorphism the object is bound to its function at run time. Since
the compiler is not able

23
Compiled By:
ER. Sachin Oli

to select appropriate function at compile time and function is linked


with particular class much
later after the compilation, this process is termed as late binding. It
is also known as dynamic
binding because the selection of the appropriate function is done
dynamically at run time.
Dynamic binding is one of the powerful features of C++. This requires
the use of pointers to
objects.

.
Polymorphism

Compile time Run time


Polymorphism Polymorphism

Function Overloading Operator Virtual


overloading functions

Er. Ranjan Raj Aryal


Amrit Campus

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:

Er. Ranjan Raj Aryal


Amrit Campus

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

Example: Virtual function in multi-level inheritance


#include<iostream>
using namespace std;
class Base
{
public:
void display()
{
cout<<"\n Display Base";
}
virtual void show()
{
cout<<"\n Show Base";
}
};

class Derived1:public Base


{
public:
void display()
{
cout<<"\n Display Derived-one";
}
void show()
{
cout<<"\nShow Derived-one";
}

};

Er. Ranjan Raj Aryal


Amrit Campus

class Derived2:public Derived1


{
public:
void display()
{
cout<<"\n Display Derived-two";
}
void show()
{
cout<<"\nShow Derived-two";
}

26
Compiled By:
ER. Sachin Oli

};
int main()
{
Base B;
Derived1 D;
Derived2 E;
Base *bptr;

cout<<"\nbptr points to base\n";


bptr = &B;
bptr->display();
bptr->show();

cout<<"\n\n bptr points to first derived \n";

bptr = &D;
bptr->display();
bptr->show();

cout<<"\n\n bptr points to derived second\n";


bptr = &E;
bptr->display();
bptr->show();

return 0;
}

Er. Ranjan Raj Aryal


Amrit Campus

“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;
}

Er. Ranjan Raj Aryal


Amrit Campus

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];

Er. Ranjan Raj Aryal


Amrit Campus

float age;
public:
person(char s[],float a)
{
strcpy(name,s);
age=a;
}

person greater(person &x)


{

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);

cout<<"Elder person is: \n";


[Link]();

P=[Link](P2);

cout<<"\nElder person is: \n";


[Link]();
return 0;
}
Output:
Elder person is:
Name: Jim
Age: 40.25
Elder person is:
Name: John
Age: 37.5

Er. Ranjan Raj Aryal


Amrit Campus

Virtual base classes:


Consider a situation where all the three kinds of inheritances, namely, multilevel, multiple and

30
Compiled By:
ER. Sachin Oli

hierarchical inheritance are involved.


Consider the following example, the “child” has two direct base class es
‘parent1’ and ‘parent2’
which themselves have a common base class ‘grand parent.
The “child” inherits the traits of ‘grand parent’ via two separate
paths. It can also inherit directly
as shown by another direct line. The ‘grand parent’ is sometimes
referred to as indirect base class
.

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
{
………………

Er. Ranjan Raj Aryal

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)

Er. Ranjan Raj Aryal


Amrit Campus

32
Compiled By:
ER. Sachin Oli

{
part1 = x; part2 = y;
}
void put_marks(void)
{
cout <<"Marks obtained:"<<"\n"
<<"part1 = "<<part1<<"\n"
<<"part2 ="<<part2<<"\n";
}
};

class sports: public virtual student


{
protected:
float score;
public:
void get_score(float s)
{
score = s;
}
void put_score(void)
{
cout<<"sports wt:" <<score<<"\n";
}
};
class result: public test, public sports
{
float total;
public:
void display (void);
};
void result:: display (void)
{
total = part1 + part2 + score;
put_number ();
put_marks ();
put_score ();
cout <<"\n Total score:"<< total<<"\n";
}
int main ()
{
result student1;

Er. Ranjan Raj Aryal


Amrit Campus

33
Compiled By:
ER. Sachin Oli

student1.get_number (678);
student1.get_marks(30.5, 25.5);
student1.get_score(7.0);
[Link]();
}

Pure Virtual Functions (Deferred Method):


It is normal practice to declare a function virtual inside the base
class and re-define it in the
derived classes. The function inside the base class is seldom used for
performing any task. It only
serves as a placeholder. For example, we have not defined any object of
class “media” and
therefore the function display () in the base class has been defined
empty. Such functions are
called “do-nothing function”.
A “do-nothing” function may be defined as follows:

virtual void display() = 0;

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
};

Er. Ranjan Raj Aryal

34
Compiled By:
ER. Sachin Oli

Amrit Campus

Virtual Base Class using Constructor

#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; }

Er. Ranjan Raj Aryal


Amrit Campus

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

Er. Ranjan Raj Aryal


Amrit Campus

36
Compiled By:
ER. Sachin Oli

 Here the student class is an abstract class since it is not used to


create any objects.
Eg:
#include<iostream>
using namespace std;
class A
{
public:
virtual void show () = 0; // pure virtual function
};
class B: public A
{
public:
void show( ) // pure virtual function is
overriden here
{
cout <<"show method is implemented here";
}
};
int main ()
{
A * ptr;
// ptr = new A; Cannot create instance of abstract class A
ptr = new B;
ptr->show( );

return 0;
}
Output:
show method is implemented here.

Differentiate Between Concrete Class and Abstract Class


An abstract class is meant to be used as a base class where some or all
functions are declared purely
virtual and hence cannot be instantiated. A concrete class is an
ordinary class which has no purely virtual
functions and hence can be instantiated.
Here is the source code of the C++ program which differentiates between
the concrete and abstract class.
The program output is also shown below.
#include <iostream>
#include <string>
#include<conio.h>
using namespace std;

37
Compiled By:
ER. Sachin Oli

class Abstract {
private:
string info;

Er. Ranjan Raj Aryal


Amrit Campus

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";

Er. Ranjan Raj Aryal


Amrit Campus

}
};
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:

……………

…………..

Friend void xyz(void); //declaration

};

 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.

A friend function possesses certain special characteristics:

1) It is not in the scope of the class to which it has been


declared as friend.
2) Since it is not in the scope of the class, it cannot be called
using the object of that class.
3) It can be invoked like a normal function without the help of
any object.
4) Usually, it has objects as arguments.

Er. Ranjan Raj Aryal


Amrit Campus

5) It cannot access the member names directly and has to use an


object name and dot
membership operator with each member name (e.g A.x)

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

{ ………..

………..

int fun1( ); //member function of x

………..

};

41
Compiled By:
ER. Sachin Oli

class Y

{ …………..

……………

Er. Ranjan Raj Aryal


Amrit Campus

friend int x : : fun1( ); //fun1 ( ) of X is friend of Y

};

Here, fun1( ) is a member of class X and friend of class Y

Example of function friendly to two classes

#include<iostream>

using namespace std;

class abc;

class xyz

int x;

public:

void setvalue(int i) { x= i; }

friend void max (xyz,abc);

};

class abc

42
Compiled By:
ER. Sachin Oli

int a;

public:

void setvalue( int i) {a=i; }

friend void max(xyz,abc);

};

void max( xyz m, abc n)

if(m . x >= n.a)

cout<<m.x;

else

cout<< n.a;

Er. Ranjan Raj Aryal


Amrit Campus

int main( )

abc j;

j . setvalue( 10);

xyz s;

43
Compiled By:
ER. Sachin Oli

[Link](20);

max( s , j );

return(0);

Example of function friendly to three classes

#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

Er. Ranjan Raj Aryal


Amrit Campus

};
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];

cout<<"\n\nSecond Employee name= "<< [Link];


cout<<"\nSecond Employee salary= "<<[Link];

cout<<"\n\nThirdEmployee name= "<< [Link];


cout<<"\nThird Employee salary= "<<[Link];

float total = [Link] + [Link] + [Link];


cout<<"\n\n Their total salary= "<<total;
}

int main()
{
E1 A;
E2 B;
E3 C;
[Link]();
[Link]();
[Link]();
process(A,B,C);
return 0;
}
Output:

45
Compiled By:
ER. Sachin Oli

Er. Ranjan Raj Aryal


Amrit Campus

Static Member Function:


A static function can have access to only other static members (functions or variables)
declared in the
same class

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 test:: count;

int main()
{

46
Compiled By:
ER. Sachin Oli

test t1,t2;
[Link]( );

Er. Ranjan Raj Aryal


Amrit Campus

[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

// CPP program without virtual destructor

// causing 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

};

class derived: public base {


public:
derived()
{ cout << "Constructing derived\n"; }
~derived()
{ cout << "Destructing derived\n"; }
};

Er. Ranjan Raj Aryal


Amrit Campus

int main()
{
derived *d = new derived();
base *b = d;
delete b;
getchar();
return 0;
}
Output

Making base class destructor virtual guarantees that the object of


derived class is destructed properly,
i.e., both base class and derived class destructors are called. For
example,

// A program with virtual destructor

#include <iostream>
using namespace std;

class base {
public:
base()
{ cout << "Constructing base\n"; }
virtual ~base()
{ cout << "Destructing base\n"; }
};

class derived : public base {


public:
derived()

48
Compiled By:
ER. Sachin Oli

{ cout << "Constructing derived\n"; }


virtual ~derived()
{ cout << "Destructing derived\n"; }
};

int main()
{
derived *d = new derived();
base *b = d;
delete b;
getchar();
return 0;
}
Output

Er. Ranjan Raj Aryal


Amrit Campus

Note: As a guideline, any time you have a virtual function in a class,


you should immediately add a
virtual destructor (even if it does nothing). This way, you ensure
against any surprises later.

Er. Ranjan Raj Aryal


Amrit Campus

Unit 7: Function Templates and Exception Handling [4hrs]


Template

 Template is a new concept which enable us to define generic class


es and functions and
thus provides support for generic programming.
 Generic programming is an approach where generic types are used as
parameters in
algorithms so that they work for a variety of suitable data
types and data structures.
 A template can be used to create a family of classes or functions.
 Since the template is defined with a parameter that would be
replaced by a specified data
type at the time of actual use of the class or function, the
templates are sometimes called
parameterized classes or function.
Format:

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()

Er. Ranjan Raj Aryal


Amrit Campus

{
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

Class Template with multiple parameters:


template <class T1, class T2, ……..>
class class_name
{
……………….
……………….
………………. // Body of the class
……………….
};
Example
#include<iostream>
using namespace std;
template <class T1, class T2>
class Test
{
T1 a;
T2 b;
public:
Test (T1 x, T2 y)
{
a = x;
b = y;
}
void show()
{
cout<<a<<" and "<<b<<"\n";

Er. Ranjan Raj Aryal


Amrit Campus

}
};
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;

template <class T>


void swap1(T &x, T &y)
{
T temp = x;
x = y;
y = temp;
}

void fun (int m, int n, float a, float b)


{
cout <<"m and n before swap: "<<m<<" "<<n<<"\n";
swap1 (m,n);
cout <<"m and n after swap: "<<m<<" "<<n<<"\n";

cout <<"a and b before swap: "<<a<<" "<<b<<"\n";


swap1(a,b);
cout <<"a and b after swap: "<<a<<" "<<b<<"\n";

Er. Ranjan Raj Aryal


Amrit Campus

52
Compiled By:
ER. Sachin Oli

int main()
{
fun(100,200,11.22,33.44);
return 0;
}

Function Templates with multiple parameters:


Template<class T1, class T2, ………>
returntype functionname (arguments of types T1, T2….)
{
……………………..
…………………….. // Body of function with type T
……………………..
}
Example

#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;
}

Overloading of template functions:


A template function may be overloaded either by template function or
ordinary functions of its
name. In such cases, the overloading resolution is accomplished as
follows:
1. Call an ordinary function that has an exact match.
2. Call a template function that could be created with an exact match.
3. Try normal overloading resolution to ordinary functions and call the
one that matches.

Er. Ranjan Raj Aryal


Amrit Campus

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;
}

Type conversion using Template:


/*----------Rectangle to polar using Template and one class to another
class type conversion using
the concept of Template--------------*/
#include<iostream>
#include<math.h>
using namespace std;
template<class T>
class rectangle
{ T x;
T y;
public:
rectangle(T a,T b)
{ x=a;
y=b;
}
T get_x()
{ return(x);
}
T get_y()
{ return(y);

54
Compiled By:
ER. Sachin Oli

Er. Ranjan Raj Aryal


Amrit Campus

};
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

 Exceptions are runtime anomalies or unusual conditions that a program may


encounter while
executing
 Anomalies might include conditions such as division by zero, access to an array
outside of its
bounds or running out of memory or disk space.
 Exception handling is a new feature added to ANSI C++

Basics of Exception Handling

Er. Ranjan Raj Aryal


Amrit Campus

 The purpose of exception handling mechanism is to provide means to detect and report an
“exceptional Circumstances” so that appropriate actions can be taken.

 This mechanism suggests the following tasks:


o 1. Find the problem (Hit the exception)
o 2. Inform that an error has occurred (Throw the exception)
o 3. Receive the error information (catch the exception)
o 4. Take corrective actions (Handle the exception)
 “ try “
 The keyword try is used to preface a block of statements
which may generate
exceptions.
 “ throw “
 When an exception is detected, it is thrown using a throw
statement in the try block
 “ catch “
 “ catch “ catches the exceptions thrown by the throw
statement in the try block.

Note: The catch block that catches the exceptions must immediately follow the try block that
throws the
exception.

General form:

Er. Ranjan Raj Aryal

56
Compiled By:
ER. Sachin Oli

Amrit Campus

--------------

--------------

try {

---------

---------

Throw exception; // block of statements which detects and


throw an exception

----------

----------

catch(type argument) // catches exception

----------

----------- //Block of statements that handles the exception

---------

----------

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);
}

Er. Ranjan Raj Aryal


Amrit Campus

}
catch(int i)
{
cout<<"Exception caught : x= "<<x<<"\n";
}
cout<<"END" ;
return 0;
}

Throw Point outside “ try “ block

type function(arg list) // function with exception


{
…….
…….
throw (object); // throws exception
…….

Er. Ranjan Raj Aryal

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";
}

else // There is a problem


{

throw(x-y); // throw point


}
}

59
Compiled By:
ER. Sachin Oli

int main()
{
try
{

cout << "we are inside the try block \n";


divide(10,20,30); // invoke divide()
divide(10,10,20); // invoke divide()
}
catch(int i)
{
cout << "caught The exception \n";

Er. Ranjan Raj Aryal


Amrit Campus

}
}

Multiple Catch Statement


 It is possible that a program segment has more than one condition to throw an
exception
 In such cases, we can associate more than one catch statement with a ‘ try ‘.

Example:
#include<iostream>

using namespace std;

void test(int x)

try

if(x==1) throw x; // int

60
Compiled By:
ER. Sachin Oli

else

if(x==0) throw 'x'; // char

else

if(x==-1) throw 1; // double

cout<<"END of try block \n";

catch(char c) // catch 1

cout << "caught a character \n";

catch(int m) // catch 2

cout << "caught an integer \n";

Er. Ranjan Raj Aryal


Amrit Campus

catch(double d) // catch 3

cout << "caught a double \n";

61
Compiled By:
ER. Sachin Oli

cout << "End of try catch system \n\n";

int main()

cout << "Testing multiple catches \n";

cout << "x==1 \n";

test(1);

cout << "X==0 \n";

test(0);

cout << "X==-1 \n";

test(-1);

cout << "x==2 \n";

test(2);

Er. Ranjan Raj Aryal


Amrit Campus

Catch All Exceptions

62
Compiled By:
ER. Sachin Oli

 Catch Catches all exceptions, irrespective of their type.


Example

#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)

Er. Ranjan Raj Aryal


Amrit Campus

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

Unit 8 File Handling [6Hrs]


INTRODUCTION

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

Stream Class Hierarchy

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:

Ifstream filename(“filename<with path>”);

OR

ofstream filename(“filename<with path>”);

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

Reading Data by getLine () Method:

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;
}

Using get and put Methods and Detecting End of File

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

Detecting End of File using EOF() member function

#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;
}

Detecting End of File using Filestream Object


#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
char ch;
[Link]("G:\\[Link]");
while(fin)
{
[Link](ch);
cout<<ch;
}

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

Reading and Writing by Using Read() and Write Member Functions


Files streams include two members functions specifically designed to input and output binary
data
sequentially: write and read. The first one (write) is a member function
of ostream class inherited by
ofstream and read is a member function of isstream class that is
inherited by ifstream. Objects of class
fstream have both members. Their prototypes are:
Syntax for write()
[Link] ((char*)&object,sizeof(object))
Syntax for read()
[Link] ((char*)&object,sizeof(object))

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;
}

Writing multiple objects to file


#include<iostream>
#include<fstream>

Amrit Campus

using namespace std;


class Student
{
private:
int roll;
char name[20];
char address[20];
public:
void read_data()

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

Reading multiple objects from file

#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;
}

Random Access File Access

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.

The streampos approach requires that you first call a “tell”


function; tell() for an ostream or
tellg() for an istream. (The “p” refers to the “put pointer” and “g”
refers to the “get pointer”). This
function returns a streampos which you can later use in calls to seekp
() for an ostream or seekg () for an

72
Compiled By:
ER. Sachin Oli

stream. The second approach is a relative seek and uses overloaded


versions of seekp() and seekg(). The
first argument is the number of characters to move, it can be positive
or negative.
The second argument is the seek direction. Some important member
functions are:
seekg(): It is used to move reading pointer forward and backward.
Syntax:
[Link] (50,ios::cur);// Moves 50 bytes forward from current
[Link] (50,ios::beg);// Moves 50 bytes forward from beginning

[Link] (50,ios::end);// Moves 50 bytes forward from end

seekp ():-It is used to move writing pointer forward and backward

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

[Link] (50,ios::end);// Moves 50 bytes forward from end

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

/*--------Program to read third object from the file [Link]--------*/


#include<iostream>
#include<fstream>
using namespace std;
class student
{
int roll;
char name[20];
char address[20];
public:
void display()
{
cout<<"Rollno:"<<roll<<endl;
cout<<"Name:"<<name<<endl;
cout<<"Address:"<<address<<endl;
}

};
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;
}

/*-------------Update/Modify the content of the file------------ */


#include<iostream>
#include<fstream>
#include<string.h>
#define N 2
using namespace std;
class Student
{
public:
int rollno;

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

/*---------------- Program to Count Number of objects from file------------------------*/


#include<conio.h>
#include<iostream>
#include<fstream>
#define N 2
using namespace std;
class Student
{
private:
int rollno;
char name[20];
char address[20];
public:
void read_data()
{
cout<<"Enter rollno"<<endl;
cin>>rollno;
cout<<"Enter name"<<endl;
cin>>name;
cout<<"Enter address"<<endl;
cin>>address;
}
};
int main()
{
Student s;
ofstream fout;

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

You might also like