0% found this document useful (0 votes)
3 views52 pages

Unit 3

Uploaded by

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

Unit 3

Uploaded by

kadama.soham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

with

Vorking ith
Inherit
Inheritance in C++, Pointers to Objects, Input-Output and Manipulators in C++ 107

Chapter 3

Working with Inheritance in C++,


Pointers to Objects, Input-Output and
Manipulators in C++

3. Working with Inheritance in C++


3.2 Pointers to Objects and Virtual Functions
3.3 Input-Output and Manipulators in C++
Questions

3.1 WORKING WITH INHERITANCE IN C++:


3.1.1 Introduction:
Inheritance is a mechanism of deriving a new class from the old class in such a way
that the new class inherits all the members of the old class. In other words, inheritance
acilitates a class to acquire the properties and functionality of another class. The new
dass depicts the acquired properties and behaviour of the existing class as well
as its
Own unique properties and behaviour.
Inheritance allows code reusability. This implies, it facilitates classes to reuse the
existing code. The new class acquires those members of the previous class
that are
already tested and debugged. Hence, inheritance saves time as well as increases
reliability.
the
3.1.2
Types of Inheritance:
epending on the number of classes involved and the way the classes are inherited,
anheritance can be of several types. These are:
ClassA Class B
Class A

Class C
Class B

(ii) Multiple Inheritance


(i) Single Inheritance
Class A
Class A

Class B Class B Class C) Class D

(iv) Hierarchical Inheritance

Class C

(iii) Multilevel Inheritance


class
A

class (class
B C

class
D
(v)
Hybrid Inheritance
3.1.3 Public, Private and Protected Inheritance:
Base Class and Derived Class:
Employee

Full Time Contract


Fig. Inheritance
inheritance
ance in Ct+, Pointers to Objects, Input-output
working win and Manipulators in C++
109
inherit.ance the class that is inherited
in parennt class. The class that inherits by the new class is called base class or super
1SS Or the members of the old class is called derived
suD class or child clase
class or
mple, in the above figure, employee is
examnpl
For a base class inherited by the derived
Fulltime nd Contract.
lasses Fu
classes
ddition to the base class members the derived
in class also contains its own
members.
Derived Class
pefining a
tance iis implemented while
Inheritance defining the derived class. The name of the base
feSDecified
specifiec in the derived class definition.
Since the derived class is nonex
class is nexistent,
a base cla
lass is defined, the inheritance is implemented only at the time of derived
class
definition.
Syntax:
drivedClassName:access-specifier base_ClassName
class

1/data members and member functions


//of derived classs

Program to demonstrate the accessibility of the Base class members Inside a Derived
class:
#include<iostream.h>
#includecconio.h>

class base

int b_pri;
protected:
int b_pro;
public:
int b_pub;
void setCO

b_pri-1;
bpro=2;
bpub-3
int get pri)

return b-pri;

Class derived:publ1ic
base
public:
void show)
private member not // directly
get-pri); 77
jaccessible member: "<<
le. NPrivate
Vipul'sM Object Oriented rOgramming
Programmi
withc WoIk

110 " "<<b_pro;


cout<<"\nProtected member:
"<<b_pub;
cout<<"\nPublic member:

|}
void main()

clrscr():
derived d;
d.set
d.show);
getch):

Output:
Private member: 1
2
Protected member:
Public member: 3 members (public, protected and private)o p
inherits all the
Note that the derived class
access only the public and protected member inE
the base class, however, it can directly protected and public member
are accessed indirectly using the
The private members
functions of the base class.
Table 1
Accessibility of Base Class Members
Base Class Accessibility by objects of
|
Accessibility Inside
Members Base Class Members the DerivedClass
Public Accessible Accessible
Protected Not Accessible Accessible
Private Not Accessible Not Accessible
Access Specifier of the Base Class:
t
The access specifier of the base class in the derived class definition determines
way the derived class inherits the base class. It determines the access specifier oftne
members ofthe base class inside the derived class. The access specifier of a base clas
member in the derived class depends on the access specifier provided while defining
derived class. Depending on the access specifiers public, protected base
or private, a
class can be inherited publicly, protectedly or privately
respectively.
Publicly Inherited Base Class:
When the access specifier of the base the
class in the derived class definition is public,
puoin
base class is publicly inherited. The access emains
specifier
the same in the derived class. This of the base class me
implies, the public members of the base class
thepublic members of the derived class and protected
rema
e
the protected members of the derived members of the base cled
class.

Vo-
nce in C++.
inhentance C++, Pointers to Objects, Input-Output
and Manipulators in Ct+ 111
slrking
with

Base Class
Private Members
Protected Memberss
Public Member

Derived Class
Private Members

Protected Members
Public Member

Fig. Publicly Inherited Base Class


access only the
when a base class is publicly inherited, the derived class object can
otblic members of the base class. The protected members
of the base class are
pud
inaccessible by the objects of the derived class. However, they are accessible to
the

member functions, friend classes and the friend functions of the derived class.

Program to demonstrate
-
Publicly Inherited Base ClasS:
#inciudeciostream. h>
#inciudecconio.h»

ciass basse

int b_pri;
protected:
int bpro;
pubiic:
int b_pub;
void setO

b_pri=1;
b_pro=2;
b_pub=3;

tlass derived: public base

private:
protected:
public
void shoaO

coute<"\nPrivate member:"<cb_pri;
Cout&"\nProtected member: "<<bpro;
Cout"\nPublic member: "<<b_pub;

vid nainO
112

clrscrO;
are accesSible in derivved class"
derived d; class
of base
************************t"
members
d.set); Following Data
COut<<"\n***********************
Cout<"\n

d.show); "<cd.b_pri;
accessible outside":
member:
cout<"\nPrivate member: "<<d.bpro; are
/7
cout«"\nProtected members of base class
cout<<"\n\nFollowing data
"<<d.b_pub;
cout««"\nPublic member in main:
getch():
class
Output: are accessible in derived
members of base class
Following Data
2
Protected member:
Public member: 3
accessible outside
Following data members of base class are

Public member in main: 3


Protectedly Inherited Base Class:
Base Class
Private Members

Protected Members
Public Members

Derived Class

Private Members

Protected Members

Public Members

Fig. Protectedly Inherited Base Class


cted
When the access specifier of the base class in the derived class definition is proe
the
the base class is protectedly inherited. Both the public and protected members
base class become the protected members of the derived class. annor
When a base class is protectedly inherited, the objects of the derived
access the public and protected members of the base class. However, these n
claers
of

iend
thebase class can be accessed by the member functions, the friend classes an
functions of the derived class.
with
aritance in C
inheritance Ct*, Pointers to Objects, Input-Output
and Manipulators in C++ 113
Hwis

Frogramto
demo
demonstrate Protectedly Inherited Base class:
gincudesiostream. h>
inc1vdesconio. h>

base
class
int bpri;
protected:
int bpro;
public:
int bpub;
void set(

b_pri-1;
bpro-2;:
bpub-3;

ciass derived : protected base

private:
protected:
public:
void show)

base::set();
// cout<<"\nPrivate member: "<<b-pri;
cout"\nProtected member: "<<b_pro;
cout<<"\nPublic member: "<<b_pub;

void rainO0

cirserO:
derived d;
I/d.setO;
in derived class";
cout«<"\n Fol1owing Data members of base class are accessible
coute"\n******* ********************** *****************"
4.shonO:
/cout««"\nPrivate member: "<<d.b-pri;
i cout<«"\nProtected member: "<<d.b-pro;
outside";
E n\nFollowing data members of base class are accessible
E n*******ttttt*t***t*tt************** ****** ****** *"
cout&"\nPublic member in main: "<<d.bpub;
9etch
Vipul'S OOJe u ramming
rTOgrammin
WihC
114

1n derived class
Output: are accessible
members of base class
|FOTlowing Data
2
Protected member:
3
Public member:
are accessible outside
Following data members of base class

Privately Inherited Base Class:


Base Class
Private Members
Public Members

Protected Members

Derived Class

Private Members

Public Members

Protected Members

Fig. Privately Inherited Base Class


When the access specifier of the base class in the derived class definition is private.
the base class is privately inherited. In this case, both the public and protected members
of the base class become the private members of the derived class.
When a base class is privately inherited, the objects of the derived class cannot access
the public and protected members of the base class. However, these
members of the base
class can be accessed by the member functions, the friend
classes and the friend
functions of the derived class.
Program to demonstrate Privately Inherited Base class:
#include<iostream.h>
#include<conio.h>

class base

int bpri:
protected:
int b_pro;
public:
int b_pub;
void set()

bpri-1;
bpro-2;
b_pub=3;
nheritanc
heritance in C++, Pointers to Objects, Input-Output and Manipulators
l
115
WIth in Ct
twAinN

derived:private base
/class
private
protected
pub7icshowC)
void

base::set);
cout<e"\ rivate member: "<<b_pri;
ute"\nProtected member: "<<b_pro;
cout<"\nPublic member: "<<b_pub;

main(0
oid
clrscr);
derived d;
//d.set);
lte"\n Following Data members of base class are accessible in derived class"
cout"\n************s

d.show);
cout««"\nPrivate member:"<<d.bupri;
/ cout««"\nProtected member: "<<d.b_pro;
/
cout"\n\nFollowing data members of base class are accessible outside";
coute\n**
/ cout<<"\nPublic member in main: "<<d.b-pub;
getch):

Output:
Following Data members of base class are accessible in derived class

Protected member: 2

Ablic member: 3

O1lowing data members of base class are accessible outside

estoring the Access Specifier of the Base Class Members:


When a base class is privately or protectedly inherited, the access specifier
of all its
access
PUDIIC and
protected members changes in the derived class. Sometimes the
need to be retained in the
Eher of a public or protected member of the base class may
This can be accomplished by declaring such a member in the derived
class
lass. original access specifier. This implies, a public member of the base class
is
With
decl
access specifier and a protected member of the base class is
erla
declared the
th public
with the protected access specifier in the derived class.
Note only the name of
the that while declaring a base class member in the derived class,
at The data type for data members or the
return type
para
nd parameter member is provided.
list are not required.
for member functions
Vipul's Object Oriented Programming
withc
116

Access Specitier of the Base Class


Class memb
Restoring the
Program to demonstrate -
#include<iostream.h>
#include<conio.h>>

class base

int bpri
protected:
int b_pro;
public:
int bpub;
void set)

b_pri=1;
b_pro=2;
b_pub-3;

class derived:private base


{
private:
protected:
public:
base: set;
base::b_pub;
void show)

// cout<"\nPrivate member:"<<b_pri;
cout«"\nProtected member:"<<b_pro;
coute<"\nPublic member: "<<b-pub;

void main()

clrscrO
derived d;
d.set)
cout<<"\n Followi ng Data members of base class are
accessible
cout<<"\n************************************************"
in derived class
d.showO;
// cout«<"\nPrivate member: "<<d.b_pri;
// cout««"\nProtected member: "<<d.b-pro;
cout<<"\n\nFoll owi ng data
members of base class are
coutk"\n*********************************** accessible outsi de";
*********s* * **"
cout<"\nPublic member in main:"<<d.bupub;
getch ();
117
aitance în C*, Pointers to Objects, Input-Output and Manipulators in C++
Inhe
WvNNh

Output: Data members are accessible


ata
/Following
of base class in derived class
****************
/**** member: 2
protected
ember: 3
public
datadata members of base class are accessible outside
Fo7lowTng9
*********** ****d************* *********************
publicmember 1nmain: 3
When
tause which access modifier while inheriting the classes?
be imherited with the public specifier if the access specifier
of
The base class should
the base class is not required to be altered.
the members of
base class should be inherited with the private specifier if the members ot the
The
base class are
not required to be further inherited.
The base class should be inherited with the
protected specifier if the members of the
base classes are to be hidden
outside the class, but can be further inherited.
Class:
llocating Memory to the Objects of Base Class and Derived the
The total number of bytes allocated
to an object of a class is equal to the sum of
allocated to the public, protected and private data members of the class. However,
bytes
the size of an object of the derived class is equal to the sum
of the size of all the data
members of the derived class and the base
class.

Program to demonstrate Memory Space Occupied by The Base


Class and the Derived
class Objects:
#include<iostream. h>
#includeeconio.h>

class base

int b_pri;
protected:
int b_pro0
public:
int bpub;

class derived:private base

private:
char name[20];
protected:
float f;
publi

void mainO

clrscrO:
base
b;
derived
d;
11S
"<<sizeof(b):
Base class: "<<sizeof(d);
cout««"\n Size of Derived cass:
cout<<"\n Size of
getch0

Output:
6
Size of Base ciass:
Size of Derived class: 30
Single Inheritance a single base class, it is
referred to
+
as sin
inherits from
When a derived class members
In single inheritance, the derived clas inherits all the of all itsbas
inheritance. protected members of the base clasc
directly access the public and
class and can
Program to demonstrate Single Inheritance:
#inciude<iostream.h>
#include<conio.h>

class person

char nane [30];


int age;
public:
void getdata)

cout<<"\nEnter name:";
cin>>nane;
cout«"\nEnter age:";
cin>>age;

void showdata ()

cout<<"\nName: "<<name;
cout<«"\nAge: "<<age;

class employee:public person

int salary;
public:
void getsal )

cout<"\nEnter salary:";
cin>>salary;

void showsal ()

cout«<"\nSalary: "<<salary;

void main()
C++, Pointers to Objects, Input-Output 119
nheritance in Ct+, Po
lnheritance and Manipulators in C++
Working with

cirscrO;
emp1oyee e;
Enter employees' data";
cout "\nt*** ****** ******
cout<<"\n******** ***** *"

e.getdata0;
e.getsal(O:
coute"\n\nEmployees' Info."
cout"\n******* *****"
showdata();
itsb
e.showsa7);
e.
getch);

Output:
emp 1oyees data
Enter ****** *****
*******
Enter name:
Sanjeela
age: 31
Enter 20000
Enter salary:

Employees Info.
*************
Nane: Sanjeela
Age: 31
Salary: 2000
Example 1:
Write a program to implement single inheritance from following figure. Accept and
display products flavors only with sweet.

Class Product
Data members: product_id, Name

Class Edible
Data members: Weight, price, flavor

#include<iostream.h>
#includecconio.h>
#include<string.h>

class Product

int product_id;
char Name
[801
public:
void getdata ()
Vipul'sM Object OrlentedProgramming
Programmi.
120 with
cs,

name: "i
Cout<"\nEnter product id and product
cin>>product-id>>Name;
}

void showdata ()
"<<Name;
cout«<"\nProduct Id: "<<product-id«<"\tProduct Name:

class Edible:public Product

float weight, price;


char flavor[80]
public:
void getdata()

Product::getdata();
cout«<"\nEnter weight, price and flavor: ";
cin>>weight>>price>>flavor;

void showdata ()

Product: : showdata();
cout<"\nWeight: "<<weight«<"\tPrice: "<<price«<"\tFlavor: "<<flavor;

char getflavor ()

return flavor;

void main()
{
Edible e[5];
int i;
char f[80];
forCi=0;i<5;i++)
elil.getdata();
forCi-0;i<5;i++)
strcpy(f, e[i].getflavor());
if(stremp(f, "sweet")==0))
e[i].showdata();
Inherltance
sorltance in
In C++, Polnters to Objects, Input-Output
wilth and Manlpulators In C++ 12
workling

Multiple Inheritance:
14 n A derived class inherits from more than one base class simultaneously, it is
When
inh
muitiple inheritance. In multiple inheritance, the derived class inherits a
erred to as multiple
eferhers
member of all its base class and can directly access the public and protectec
the
members the base classes.
of
am
to demonstrate Multiple
Program to Inheritance:
gincTudec10Stream. h>
pinclude<conio. h>

person
class
name [30];
char
int age;
pub1ic:
void getdata()

cout«<"\nEnter name: ";


cin>>name;
cout««"\nEnter age:";
cin>>age;

void showdata()

cout«"\nName: "<<name;
cout&«"\nAge: "<<age;

Class employee

int salary;
publi
void getsal()

cout«"\nEnter salary:";
cin>>salary;

void showsal
()

cout"nSalary: "<<salary;

class
fulltime:public person,
public employee

void main(O

clrscr)
fulltine
cOut"nfEnter
employees' data";
Vipul'sM Object Oriented ogramming
122 with
ci
f.getdata():
f.getsal (O:
cout<<"\n\nEmp1oyees' Info. ";

f. showdata();
f.showsa1 ();
getch

Output:
Enter employees' data

Enter name: Sanjeela


Enter age: 31
Enter salary: 2000

Emp1oyees' Info.
************** * * ****
Name: Sanjeela
Age: 31
Salary: 2000
Ambiguity Resolution in Multiple Inheritance:
In multiple inheritance, an ambiguity may arise when two or more
base classes have
a member with the same name. In order to resolve such
ambiguities, the name of the
member is qualified with the name of the base class by using the
scope resolution
operator.
Program to demonstrate Ambiguity in Multiple Inheritance:
#include<iostream.h>
#includecconio.h>

Class person

char name [30];


int age;
public:
void getdata()

cout««"\nEnter name:";
cin>>name;
cout<"\nEnter age:";
cin>>age;
}

void showdata()

cout«"\nName: "<<name;
cout<<"\nAge:"<<age;
serltance in Ct+, Pointers to Objects, Input-Output
Workingwith and Manipulators in C++ 123
emp oyee
c]ass
salarY
int
public: ()
void getda ta

cOut"\nEnter salary:";
cin>>salary;

void
showsal ()

"<<sal1lary;
cout <«"\nSalary:

fulltime:pub1i. person, pub1ic employee


class

mainCO
void

clrscr;
fulltime f:
coutee"\n Enter employees' data";
assesh ost"\n*************************"
amecd / f.getdata(); Ambiguity
cOut<<"\n\nEmployees' Info.";
resoli COut&<"\n*****:
************ ****"
getch);

Program to demonstrate Ambiguity Resolution in Multiple Inheritance:


includeciostream.h>
includeeconio.h>

class person

Char name
[30];
int age;
public:
void getdata()

cout<"\nEnter name: "


cin>>name;
COut<"\nEnter age:";
cin>>age;
}
void showdata()

u nName: "<<name; u riJ


Cout&"\nAge:"<cage;
Vipul's Object Orlented programming
Programmina
c
with
124

class employee

int salary;
public:
void getdata ()

cout««"\nEnter salary: ";


cin>>salary;

void showsal ()
cout«"\nSalary:"<«salary:

9
person, public employee
class fulltime:public

void main)
clrscrO
fulltimef:
cout<<"\n Enter employees' data";
cout<<"\n******************t#***t*"
f.person: :getdata(O: //Ambiguity resolved
f.employee: :getdata();
cout«"\n \nEmployees' Info. ";
cout<<"\n********************";

f. showdata):
0;
f.showsal
getch O;

|Output:t
Enter employees data
* ****t****tt*
*****ttt

Enter name: Sanjeela


Enter age: 31
Enter salary: 2000
Employees' Info.
************** 19-
Name: Sanjeela
Age: 31
Salary: 2000
Multilevel Inheritance: some
When one class is inherited from another class, which in turn is inherited troriss
Comprises
other class, it is referred to as multilevel inheritance. Multilevel inheritance con
vhich
two or more levels. The derived class is inherited from the direct base class, mbers of ors
turn is derived from another base class. Hence, the derived class has all the ncfransitive
its direct base clss as well as its indirect base class. This is known as the
nature of multilevel inheritance.
inheritan
aritance In C++, Pointers to Objects, Input-Output and Manipulators in C++ 125
with
Working

demons
Multilevel Inheritance:
Program todemonstrate
tream. h>
pincludecios
includecconio. h>

person
class
name[30);
char
age;
int
pub1ic:
()
void getdata
out«<"\nEnter name: ";
cin>>name;
cout<<"\nEnter age: "
cin>>age;

void showdata ()

cout<<"\nName:"<<name;;
cout«<"\nAge: "<<age;

person
class employee: public

int salary;
public:
void getsal()

cout"\nEnter salary: ";


cin>>salary;

void showsal)

cout««"\nSalary: "<<salary

class fulltime:pub1ic employee

char sub[30]
public:
void getsub()

name:
cout&"\nEnter subject
cin>>sub;
"
void showsub)

COut&"\nSubject to be taken: "<<sub;

void main()
Vipul'sN Object Oriented Programming
wtt
126

clrscr);
fulltime f; employees data";
cout<<"\n Enter ********** * * *s*****";
Cout<<"\n******
f.getdata):
f.getsal0:
f.getsub);
cout<"\n\nEmployees' Info. ";
Cout<<"\n********************"

f. showdata ();
f. showsal);
f. showsub);
getch ();

Output:
Enter emp1oyees' data
************************
Enter name: Sanjeela
Enter age: 31
Enter salary: 2000
Enter subject name: 0OPS
Employees' Info.
****** **************
Name: Sanjeela
Age: 31
Salary: 2000
Subject to be taken: 00PS
Example 2:
figure. Acce=
Write a program to implement multilevel inheritance from following
and display data for one student.
Class Student
Data members: Roll_no, Name

Class Test
Data members: marks 1, marks 2
due

Class Result
Data members: total
127
Input-Output and Manipulators in C++
Inheritance in C+, Pointers to Objects,
tance
with
Horking
1udeciostream.
nc1ude<conio.ha

Student
class
rollno;
int namel50];
har
pub7ic getdata()
void
"Enter student RolT no and name:";
Coute"
cim>rollno>>name;

showdata ()
void

coute"\n No: "<<rol1no«<"\tName: "<<name;

class Test:public
Student

marks1, marks2;
int

public:
void getdata()

Student::getdata()
Cout«"Enter Marks1 and Marks2: ";
cin>>markslb>marks2;:
Accep

void showdata ()

Student::showdata();
cout«<"\nMarks1:"<<marks1<<"\tMarks2: "<<marks2;

int getMarks1()

return marks1;

int getMarks20

return marks2;
128

Result:public Test
class
int total;

public:
void getdata ()
Test::getdata();

void showdata ()

Test:: showdata ();


total=getMarks1()+ getMarks2();
"<<total;
cout«"\nTotal Marks:

void main()

clrscr)
Result r 5tu7iidue 1
r.getdata();
r.showdata();
getch)

Output:
name: 101 Sanjeela
Enter student Rol1 no and 78 88
Enter Marks1 and Marks2:
Ro11 No: 101 Name: Sanjeela
Marks1: 78 Marks2: 88
Total Marks: 166
3.1.5 Hierarchical Inheritance:
one class=
Hierarchical inheritance is a type of inheritance in which more than
class provic
derived from a single base class. In hierarchical inheritance, a base
members that are common to all of its derived classes.
of
In hierarchical inheritance, each of the derived class inherits, all the members
base class. In addition, all the derived classes can directly access the publica
protected members of the base class. However, one derived class cannot access
members of another derived class.
Program to demonstrate HierarchicalInheritance:
#includeciostream.h>
#include<conio.h»

class emp1oyee

char name [30];


Inheritance
itance in C+*, Pointers to Objects, Input-Output
withi
vith and Manipulators in C++
Working 129

age;
int
public:
void
getdata ()
cout<<"\nEnter name: ".
"

cin>>name;
cout<<"En ter age: ";
cin>>age

showdata ()
void
cout<<"\nName:<<name;
cout<<"\nAge: <<age;

/class fulltime:public employe

int salary
public:
void getsal()
cout«<"Enter salary: ";
cin>>salary;

void showsa1 ()

cout"\nSalary: "<<salary;

class contract: public emp1oyee

int hrs_worked;
int wages perhr;
public:
void calsal ()

Cout<"\nEnter no. of hours worked: ";


cin>>hrsworked;
Cout<<"Enter wages per hour:"
cin>>wages_perhr;

void showcalsal ()
"<<hrs_worked*wages_perhr;
U"nTotal Salary:

void mainC

clrscr)
fulltime
Cout f
nEnter Fu11 Ti me employees data";
n*************** ** ***************
130

f.getdata();
Employees' data";
f.getsa1(); ***********d***************".
coute<"\nEnter Contract
cout<<"\n**
contract C;
c.getdata ();
c.calsa1(); Employees' Info. "
cOut<<"\n*******d**ddd****dd*******",
cOut<<"\nFul1 Time

f. showdata ();
showsal();
f.cout<<"\n\nContract Employees' Info.";
****"
cout<<"\n**********s
c.showdata);
C.showcalsal );
getch ;

Output:t
Time employees data
Enter Full
Enter name: Sanjeela
Enter age: 31
Enter salary: 20000
|

Enter Contract Employees' data


*************t***i
Enter name: Sanju
Enter age: 29

Enter no. of hours worked: 30


Enter wages per hour: 400

Fu11 Time Employees' Info.


******************** ****

Name: Sanjeela
Age: 31
Salary: 20000

Contract Employees' Info.


*******

Name: Sanju
Age: 29
Total Salary: 12000
3.1.6 Virtual Base Class:
An abstract class is a class that contains
at least one pure virtual function. In tne
declaration, if the declaration of a virtual
(0) to the function declaration member function is done by appending
then the function is pure virtual
function.
inheritan
eance in C+, Pointers to Objects, Input-Output and Manipulators 131
in C+*
#Ykingwln
example,
For
base
class
pubiic
void dis
display ) 0:
=
void
virtua
abstract class cannot be used as a parameter type, a function return type, or the
it conversion type ine most important thing is that one cannot declare the object
eNp
hctract class. However, declaring pointers and references to an stract class is
an
passible.
A virtual member runctions can be inherited, a class derived from an abstract
can
dass
also be abstract unless overriding of each pure virtual function in the derived
can also
done.
dassis
For example,
Frogramto demonstrate Abstract Base Class:
#includeciostream. h>
#include<conio. h>
Using abstract methods and classes.
class Figure

public:
dim1;
double
double dim2;
Figure (double a, double b)

dinl a;
din2 b;

I pure virtual function


virtual double area()=0;

class Rectangle: publie Figure

public:

kectangle(double a, double b): Figure(a, b)

implement area for rectangle


double
area()

utnInside
return dim1
Area for Rectangle:
*
dim2;

class
Triangle:public
Figure
132

public:
Figure(a,b)
TriangleCdouble a, double b):

for right triangle


// implement area
double area()

cout"\nInside Area for Triangle: ";


return dim1 * dim2 / 2;

void main)
ClrscrO:
Rectang1e r(9, 5);
Triangle t(10, 8);
cout<< r.area();

cout« t.area);
getch )

Output:
Inside Area for Rectangle:45
Inside Area for Triangle:440
3.1.7 Constructor and Destructor in Inheritance:
are
The constructors of the base classes and constructors of the derived class
automatically executed when an object of the derived class is created. The constructors
of the base classes are executed first and then the constructor of the derived class is
executed. In mulitple inheritance, the constructors of base classes are executed in tne
same order in which the base classes are specified in derived class(i.e. from left to right,
Similarly, the destructors are executed in reverse order, i.e. derived class constructor
is executed first and then constructors of the base classes are executed (from right to to

left).
If the constructors of the base classes have no parameters, then the syntax to c reate
relationship between derived class and base classes is very simple.
For example,
Program to demonstrate Order of calling Constructor and Destructor in ce:
#include <iostream> inheritan
using namespace std;

class parent //parent class


133
Inheri
tnheritance in C++, Pointers to Objects, Input-Output and Manipulators in C++
Working with

pubTic:

parent (
//constructor
"Parent class Constructor called\n";

parentO //destructor
cout << "Parent class Destructor called\n";

Tienf

public parent 1/child class


class child
:

public:
child) //constructor
cout << "Child class Constructor ca11ed\n";

erived e child) //destructor


Ihe cors
derive: cout << "Child class Destructor called\n";
executet
m
left:
lasscaxt;
(from

int main()
synta

//automatically executes both child and parent class

inhemi
co
constructors and destructors because of inheritance

child c;
return 0;
Vipul's Object Oriented Programm
Ogramming
134 with
C
Output:
Parent class Constructor called
Child class Constructor called
Child class Destructor called
Parent class Destructor called
3.18 Containership:
has an object of
Composition is also referred to as nesting, in which class
a of another
or aggregation or containershi.
class as its members. Composition or containment
between clase ke
inheritance, enables the implementing of a logical relationship
access only to the
nesting, the class (enclosing class) that contains an object has clae
members of that class. The private and the protected members of the contained
clase
not accessible to the enclosing class. However, in inheritance, the derived Can
access the protected members of the base class.

Program to demonstrate the composition of classes:


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

class colony

char *address; U2r2


public:
void get(0

cout<<"\nEnter address: ":


gets(address) ;

void show0

cout<"\n, "<<address;

class room

int roomno, bldgn0;


public:
colony c1;
void geto

cout<"\nEnter room number: ";


cin>>roomno;
cout"\nEnter bui lding number: ";
cin>>bldgno;
c1.getO:
void show ()

cout«"\nAddress\n";
Inheritane
heritance in C+*,Polnters to Objects, Input-Output
NvAW th and Manipulators In C 135

cout"\n-.
cou n"<eroomno
";
coute"\n «<"7 "<<bldgno;
cl.show):

mainC)
oid
ndthe clrscr);
roam r
get);
showC):
pudis r.
etch)
Output:
Enter room number: 15
Enter building number: 98
ater address: Wadala(E), Mumbai.

Address

15/ 99,
Wada (E), Mumbai.
la
between Composition and Inheritance:
Difference

Composition Inheritance
The object of one class is used as al The object of one class inherits the
member in another class. property of another class.
Does not support the concept of Supports the concept of reusability.
reusability.
Does not provide additional features Provides additional features to an
to existing class. existing class.
- KIND -
Represents 'HAS - A' relationship. Represents 'IS - A OF
relationship.
Example: Example:
House Room

Room

Dining Reading
RoomRoom L Hall
Ugr
Vipul's' Object anming with
Cs
FUNCTIONS:
136 VIRTUAL
OBJECTS AND
POINTERS TO
3.2 pointers to objects,.
3.2.1 Pointer to
Objects: variables, you can have
pointers to other types of
to an object, use the ar
Just as you have of a class given
a pointer (
members
When accessing operator.
operator instead of the dot
For example,
Pointer to Object:
Program to demonstrate
#include<iostream>
namespace std;
using
//Pointers to objects
class student
char name [20];
int age;
public:
(O
void get

cout<<"\nEnter name: ";


cin>>name;
cout«"\nEnter age: ";
ci>>age;

void show)

cout"\nName: "<<name;
cout"\nAge:cage;

int mainC t tblpt,5u

student S; lessot9
student *ptr;
S.getO;
ptr=&s;
ptr->show ();
return 0;

Output:
Enter name: Sanjeela
Enter age: 33
Name: Sanjeela
Age: 33
3.2.2 The This Pointer:
The "this"pointer is a special pointer class
currently calling the member function that contains the address of an object a callsScal15
of the class. Whenever an
object of the class
clas>
tance in C++,
Inheritance C+*, Po
Pointers to Objects, Input-Output and Manipulators
in C++ 137
with
Working **

on-static member function, the address of the object (this pointer) is passed as
implici argument (or as a hidden argument) to it and is available as a local variable
anyiit
an within its
w
body.
The ata
members of the caling object can be accessed within the member functions
directly using their names or indirectly using the'operator with this pointer. In
eitherdired
he this pointer can be used to return the object pointed to by it, to the calling
ition, the
program.

am to demonstrate this pointer:


#includesiostream. h>
#includecconio. h>
class abc

int n;
public:
abc)

n-0;

abc(int n)

this->n n
void showO

Cout<<n

abc large(abc aa)

if(n>aa.n)
return *this;
else
return aa;

void mainO

clrscr);
abc al(10),a2 (20),a3;
a3=a1.large(a2);
Cout«cendl«<"Object 1 data: ";
al.show():
cout<cendl<<"0bject 2 data: ";
a2.showC):
coute"\nLargest object data: ";
a3.show):
getch )

fa
Vipul'sM Object Oriented Programming maaahio
withc
138

Output: lhata
Object 1 data: 10
nles
heried
Object 2 data: 20 Work
Largest object data: 20 a parameter of the
same name as a mer
Note that our constructor is takingparameter and 'this > n' refers to the
Avtual
tho mbe
member class
variable. In this case, 'n' refers to the
variable.
return the object it was Class15
workino.with ASe
ed
Occasionally it can be useful to have a function was passed
object that implicitly
Returning *this' will return a reference to the the
function aplersel
3.2.3 What is Binding in C++? (arthlenlisof
to be executed resnn
Binding refers to the linking of a procedure call to the code in onseEalayingd
with a procedure that2
to the call. Dynamic binding means that the code associated given
apler
is not known until the time of the call at run-time. It is associated with polymorphic
and inheritance. A function call associated with a polymorphic reference depends onthe
kervedd
dynamic type of that reference.
At run-time, the code matching the object under current reference will be called. sebptry
3.2.3.1 Virtual Functions:
Virtual functions in C++ support run-time polymorphism. A virtual function is a Show
member function that is declared inside the base class and its functionality can be t=&cd,
overridden in the derived classes. When the base class containing virtual function is otr=Show
inherited, the derived classes may implement their own versions of that function.
Thefavirtu
entire function of the base class can be replaced by a set of new implementation in the lfa
virtua

derived class. This implies that the base class provides a common interface and this
CEember fune
interface can be implemented in different ways in different derived classes. A member
function can be made virtual by prefixing its declaration with the keyword virtual in the
base class. For example, TEhanisim
i
class Base
Eamto
public ludeciost
cludeecoi
virtual void Show()
{ cout <« "Show of base class"; assbase

Whenevera virtual function is inherited,


its virtual nature is also inherited into a l its irual
derived classes and it is not required
derived classes. For example,
to use the keyword
'virtuall in the subse Ient Vo1 voi

class derived: public Base

public:
void Show()
cout <« "Show
terive
of derived class";
ritance in C+, Point
nheritan binters to Objects, Input-Output
and Manipulators in
with Ct+
Werking 139
in.when a derived class that has inherited
ada a virtual function itself
n
base
for
class to another derived class, the virtual function can is used as
still be overridden. This
ainplhes at a virtual fun
function always remains
virtual irrespective of the number
of times
inherited
is Working of a Virtu; Function:
it323.2
..nl function must be accessed using a pointer of
base class type and not of
rived Alass type. However, if the function is not
declared virtual and the pointer of
made to point to the derived class, the function
base of the base class is always
That is, the complier selects a function on the basis of the
xeC type of pointer
instead its Contents. However, if the function is declared virtual in the base class, the
Complierselects which ich version of the function is to be executed depending upon
the
ts of the point
pointer. Moreover, this decision is made at the run-time, thereby,
ovingemploy dynamic binding. Hence, declaring a member function virtual informs the
complier that the ffunction call is resolved at run-time. For example,
endt
Base b; // object of Base class
derived d; l/object of Derived class
Base bptr; //Pointer of type base
bptr=&b; //Pointing to base class
//Show() of base class
ybptrshow0;
//Pointing to derived class
nbptr= ed;
tion
bptr= Show(); //Show() of derived class

in Ifa
on virtual function is not redefined in the derived class, a call to that function uses
the function implementation defined in the base class. Moreover, like a non-virtual
m-member
ne
function, a virtual member function can be accessed directly in the derived class
alusing the scope resolution operator (:). However, in this case, the virtual function
mechanism is suppressed and the base class implementation of the function is classed.

Program to demonstrate Virtual Function:


#includeciostream. h>
Finclude<conio.h>

class base

public:
alvirtualvoid display()
eque
coutee"nDisplay of base class called"

class derived:public base


public:
void display)
140
derived class called"
cout<"\nDisplay of

void main)

clrscr):
base *b;
derived d;
b=&d;
b->display);
getch):

Output: called
Display of derived class Function:
3.2.3.3 Rules for Virtual
functions must be members of some class.
The virtual
members.
They cannot be static
pointers.
They are accessed by using object
a friend of another class.
A virtual function can be even though it may notbe used.
class must be defined,
A virtual function in a base in the derived classes must
its redefined versions
The base class virtual function and
same prototype. However, if the prototype differs, the complier considers
have the
functionns.
these functions as overloaded
of a base cannot be made virtual, however, the destructors can be
The constructors
made virtual.
tyype of the derived object, but we cannot use a
A base pointer can point to any
pointer to a derived class to access an object of the base type.
incrementing or decrementing the pointer of base type, it will always point to
tne
On
of the
next or the previous object respectively of its base class type, irrespective
contents of the pointer.
3.2.3.4 Pure Virtual Function and Abstract Class:
If a derived class does not redefine a virtual function, the base class implementato
ngful
of the virtual function is invoked. However, in some cases, either no meanin
definition of the virtual function exists in the base class or each derived class 1S rE
to define its own version of the virtual function. To handle such cases, C++ provu vides
pure virtual functions.
A virtual function that has no definition pure
within the base class is known as a"ot
virtual function. A virtual function can be
made pure by appending thepure pu speci
nction
nction
'=0' to its declaration in the base class.
The syntax for declaring a pure virtua
is
virtual return_type functionName
(argumentlist) = 0;
with ance in C++, Pointers to Objects, Input-Output
Working and Manipulators
in C++
example: 141
For
student
class

4d Show(O = 0; //pure
virtua virtual function

fa eual function is declared as pure, it


must be redefined
classes Otherwise a program error occurs.
In addition, a virtual in all of its derived
pure pecifier and definition. function cann
not have
both
Programtodemonstrate pure virtual function:
#inc1ude<iostream. h
#include<conio.h>

class base
pub7ic:
irtual void show)=0; // pure virtual1 function

dclass chi1dl:public base 9


public:
void show

cout«"\nShow method of child1 called";

class child2: public base

public:
void showO

coute«"nShow method of chi1d2 called";

void main()

clrscrO;
child1 c1;
cl.show);

child2 c2;
c2.show):
getch)
142 P** Jett onened ri8rdmmine
win

Output:
Show method of child1called
Show method of child2 called
Example:
and 'rectangle from clase
Create class Shape. Derive two classes 'triangle
rectangle to accept dimensipe
Write appropriate functions in class triangle and
for calculating area. Here make area) function virtual w
triangle and rectangle
and rectangle interactivel.is
common for all and which will calculate area of triangle
#include<iostream.h>
#include<conio.h>

class Shape

public:
virtual int Area()=0;

class Triangle:public Shape

int base, height


public:
void getdata ()

cout<<"Enter base and height of triangle: ";


cin>>base>>height;

void showdata ()

cout<"\nBase: "<<base««"\tHeight: "<<height;

int Area()

return (base*height)/2;

class Rectangle: public Shape

int width, height;


public:
void getdata()

cout<"\nEnter width and height of rectangle: ";


cin>>width>>height;

void showdata ()
Inheritanr in Ct+, Pointers to Objects,
o
Input-Output
with and Manipulators
working in C++
143
\nWidth: "width«<"\tHei
cout<"| "<<height

Area(
int
n (width*height);

y.
mainC
void
clrscrO;
int a t;
Triangle
t.getdata();
Rectangler;
r.getdata(;
showdata(0;
t.at.Area() :
COut<"\nArea of triangle: "<<a;

r.showdata);
a=r.Area();
cout&"\nArea of rectangle: "<<a;
getch);

Output:
Enter base and height of triangle: 12 6
Enter width and height of rectangle: 12 13
Base: 12 Height: 6
Area of triangle: 36
idth: 12 Height: 13
Area of rectangle: 156
3.2.3.5
Object Slicing:
When a derived class object is passed by value as a base class object, as in foo(Base
derived_obj),
the base class copy constructor is called. So, the specific behaviours of a
EIVed class object are sliced off. We're left with a base class object. In other words, if
pcast(Upcasting and Down Casting) to an object instead of a pointer or reference,
is sliced. As a result, all that remains is the sub object that
corresponds to the
Aect
destination
typ of our cast as shown in the example beloW:
Pr
Ogram to demonstrate object
includeciostream.h> slicin8
#includecconio.h>

Class
8
gramimin,
Hth
144

public:
int i
B
class D : public

public:
int ji

int main)

B B1;
DD B1
B1 = D1; //only i is copied to

Function:
3.2.3.6 Some Facts about Virtual objects of class. virtual mechani
Virtual functions can be called explicitly using
works only in case of pointers to object.
A pure virtual function can have body
but in no way we can use this body,
3.2.3.7 Virtual Destructor:
its behaviour is determined
A virtual method has no direct implementation and
the method with the same signature that
is on the lowest inheritance level of t
object is destroved.
instantiated object. A destructor is automatically called when the
virtual destructor in C++ is used primarily to prevent resource leaks
by performine
clean-up of the object.
The following steps explain how to use virtual destructors:
.Determine when to use a virtual destructor. A destructor for a class should be virtual
when an object of a derived class will be destroyed by invoking the base clas
destructor. The destructor must be virtual when you delete a pointer to an objectand
it is possible that it points to a derived class.
The difference between a destructor and other methods is, in both cases, the metho
of the derived class is invoked if it is implemented. However, the base clas
destructors is subsequently called whereas this does not happen with other methous
For example,
Program to demonstrate Virtual Destructor:
#include<iostream.h>
#include<conio.h>

class base

public:
base()

cout<endl«<"Base class
constructor called";
Inheritance in C++,
Ct+, FPointers to Objects, Input-Output and
Norking with
Manipulators in C++ V"V"V" 145

virtualbase()

zend1«<"Destructor of base class called";

c1ass
derived:public base

public
derived()

Out<<endl <<"Derived class constructor called";

derived()

cOut<eend1<<"Destructor of derived class called";

nte ain()
void
DyClrscr();
derived *d= new derived ();
delete d;
getch():
hr
Output:
class constructor cal1ed
Base
Derived class constructor called
Destructor of derived class called
Destructor of base class called

Observe the use of the virtual keyword in the above program (virtual base () ). If -
the destructor of the base class were not declared as virtual, the destructor of the
derived class would not get called.
Implement at least an empty body for a virtual destructor, since a pure virtual
function cannot be declared.

3.3 INPUT-OUTPUT AND MANIPULATORS IN C++:


3.3.1
Introduction, C++ Stream Classes:
In C++ the
1/0 operations are carried out by streams. A stream is a sequence of bytes.
in caseofinput, the input stream flows from the external device to the main memory
puter and in case of an output, a stream of bytes flows out of main memory to the
Pdevice. In case of standard input the stream comes from keyboard and for
146 Vipul'sM Object Oriented Programming
withc
standard output the stream flows from main memory to the monitor. Howes.
ase of input andthe
stream may be redirected from devices other than keyboard in case andcanbe
nd output streams
directed to devices other than monitor in case of output. The input and
are illustrated in Fig. below:
input stream
Input
device
Programn

output stream
Output
device

Fig.: Input/ Ontput streams


The ios class:
The iostream library:
When you include the iostream header, you gain access to a whole hierarchy of
classes responsible for providing 1/O functionality (including one class that is actually
named iostream). The class hierarchy for the non-file-1/O classes looks like this:

ios_base

ios

istream Ostream
(input) (Output)

istream_withassign ostream_withassign
(cin) lostream (cout, cerr, clog)

iostream_withassign
,
Fig
.ritance in C#+
Inheritance C++, Pointers to Objects, Input-Output
and Manipulators in C++ 147
werking with

thing you may notice about this hierarchy is that it uses


thin
The first
irst multiple inheritance.
o.
However, the
the iostream ibrary has been designed and
extensively tested in order to
any of the typical multiple inheritance problems, so you can use it freely without
of
avoid
worrying
The am class is the primary class used when dealing with input streams. With
istream
input.streams, the extraction operator (>>) is used to extract the values from the stream
ne

so it can
be used.
he Ostream class is the prinmary class used when dealing with output streams. With
Th
output streams, the insertion operator (<) is used to put values in the stream
uses them.)
(e.g. monitor
The iostream class can handle both input and output, allowing bidirectional 1/O.
Finally, there are a bunch of classes that end in "_withassign". These stream classes
are derived from 1stream, ostream, and iostream (respectively) with an assignment
anerator defined, allowing you to assign one stream to another. In most cases, you won't
opera
bedealing with these classes directly.
Standard streams in C++:
A standard stream is a pre-connected stream provided to a computer program by its
IS. environment. C++ comes with four predefined standard stream objects that have
already been set up for your use. The first two, you have seen before:
) cin: an istream_withassign class tied to the standard input (typically the
keyboard)
(2) cout: an ostream_withassign class tied to the standard output (typically the
monitor)
(3) cer an ostream_withassign class tied to the standard error (typically the
monitor), providing unbuffered output
(4) clog: an ostream_withassign class tied to the standard error (typically the
monitor), providing buffered output
Unbuffered output is typically handled immediately, whereas buffered output is
typically stored and written out as a block. Because clog isn't used very often, it is often
omitted from the list of standard streams.
Input with istream:
When reading strings, one common problem with the extraction operator is how to
Keep the input from overflowing your butfer. Given the following example:
char s[10]; cin>>s;
What happens if the user enters 18 characters? The buffer overflows, and bad stuff
happens.

ne way to handle this problem is through use of manipulators. A manipulator is an


(>>) or insertion
is used to modify a stream when applied with the extraction
nat
perators. One manipulator you havealready worked with extensively is "endl",
oth prints a newline character and flushes any buffered output.
Programs
Vipul's" Object Oriented with c
C+
iomanip.h he: header) that
148 (in the setw Cn be
known as setw from a stream. 1o use
manipulator
C++ provides a mi characters read in a parameter, andd ins mp
insert
used to limit the number of characters to read as it into
provide the max 1aximum number of
159112
your input statement like such:
#include <iomanip.h> stream 1
char s10]; cin>>setw(10)>>s; first 9 characters out of the
only read the left in the stream until +h next
will now characters will be
hisforprogram
a terminator). Any
remaining
$pace
is that the extraction Ona
perato,
extraction. to mention so far newlinor
omitted tabs, and nes).
thing that we have
ne one "formatted" skips whitespace (blanks,
data that
- is, it
Works with
program:
Take a look at the following
void mainO

char ch;
while (cin >> ch)
cout << ch;

When the user inputs the following:


come to the wor1d of c++
Hel1o everyone we1
skips the spaces and the newline. Consequently, the output is:
The insertion operator
Hel1oeveryoneweIcome tothewor1dofc++
you'll want to get user input but not discard whitespace. To do this, the
Oftentimes, can be used for this purpose.
istream class provides many functions that
the useful is the get) function, which simply gets a character from the
One of most
input stream. Here's the same program as above using get):
void main()

char ch;
while (cin.get(ch) )
cout << ch;

Now when we use the input:


Hello everyone wel come to the wor1d of c++
The output is:
He11o everyone welcome to the wor1d off C++
Drawback of get) is:
get) read up to the newline and then stopped.
Consequentily, there is another function called getline() that works exactly like get0
ut reads the newline as well.
id main)

char s[11];
// Read up to 10 characters
cin.get1ine (s, 11);
neade
inneritancei
ance in C++, Pointers to Objects, Input-Output and Manipulators in 149
Witn C++
x, Working
and cout << s << end1;
o 10 more characterss
Read up to
cin.getline(s,end1;11);
<<
cout < s
ne nore useful istream functions:
ceam tea Few
we are a few more useful
discards the first
input functions that you might want to make use of:
urt ignore( character in the stream.
ignore(int discards the first n characters.
n):
xtracion
and peek0: allows you to read a character from the stream without removing it from the
De Pstream.
11nget0:
ui ge
returns the last character read back into the stream so it can be read again
by the next call.
nutback(char c) allows you to put a character of your choice back into the stream to
put
be read by the next call.
3.3.2 Unformatted Input/Output .

get) and put():


function of class istream and the function put) is a
The function get() is a member
ember function of class ostream. Both the functions are meant to deal with single
y,theoucharacter.
me
Thus get) is used to read single character from an input device and function
Dut) is used to write a character to output device.
e.Todot The function get() fetches a single character which includes white space characters
and eof. It has to be used with an object of class istream, for example, cin.get().
naractet
fre
cin.getCO;
char C;

C cin.get();
Program to demonstrate get():
#include<iostream>
void main ()

char ci
cout <"Enter a character:";
C cin. get);
cout <<"The character c = "<< C << endl;

Output:
Enter a character :A
The character c = A
getline
The function is object .for reading complete line, for instanc-
xactly le Cin.getline(). used with istream

two or three arguments as illustrated below.


dn Char take
c[ 1= "C++ is fun";
Cin.get1ine(c, size_t n))i
n.getline (c, size_t n, char delimit);
Vipul's'M Object Oriented Programming
with C

P'rogram to demonstrale getline):


*include <iostream>
void main)

char name[ 30] ;


cout "Enter a name : ":
cin.getine(name,30);
name
cout"You have entered the

Output:
Enter a name: Sanjeela
name: Sanjeela
You have entered the
read) and writel): stream
functions read() is a member function of istream and is used with input ams
The hence it i
is a member function of ostream and
such as cin.read(). The function write()
The function write() does output of a
used with output streams such as cout.write().
memory without any formatting
number of bytes from the character array in the some bytes without anv
read() does input into the memory
Similary the function
() take two arguments as illustrated
formatting. Both the functions read() and write
below.
char name[15);
cin.read (name,15);
cout.write(name, 15);
|Program to demonstrate write() and read():
#include <iostream, h>
Void main)

char cl "Sanjeela Sagar":


cout.nrite(c, 13). put(' \n'); // put('\n')is used
// in p1lace of end1
char ch = "A":
cout««"ch = ";
cout.write(ch,1)<<endl; / asked to write one
//byte of ch.
char s[ = "ABCDEFGHIJC"
cout.write(s, 5)<cendl; // asked to write 5

// bytes/characters
char name [15];
cout«"Enter a name: "
cin.read(name ,15): // asked to read 15 bytes/char
cout.write( name, 15) <cendl; /1 asked to write 15
//bytes from Name
inheritance
eritance in C++, Pointers to Objects, Input-Output
Working with and Manipulators in Ct+

Output:
Sanjeela Sagar
ch A
ABCDE
name: Rakesh
Enter a
Rakesh
3.3.3 Formatted Input /Output Operations:
re are two ways to change the formatting options:
There
flags, and manipulators. You
can hink of flags
as boolean variables that
can be turned on and off. Manipulators are
objectsplaced in a stream that affect he way things are input and output.
To Switch a flag on, use the setf0 function,
To with the appropriate flag as a parameter.
For example, by default, C++ does not print a + sign in front of positive numbers.
Howevever, by using the ios::showpos flag, we can change
:showpos); this behavior:
cout.setf(ios: // turn on the ios::showpos flag.
cout << 10 << end1;
This results în The following output:
+10
It 1S possible to turn on multiple ios flags at once using the OR C1) operator:
cout.setf(ios:: showpos ios::uppercase): /7 turn on thne
1/ios::showpos and ios::uppercase flag
cout << 10 << end1;
To turn a flag off, use the unsetf) function:
cout.setf(10s: :showpos); /7 turn on the
1/ios:: showpos flag
cout << 10 << end1;
cout.unsetf(ios::showpos); I/ turn off the
I/ ios::showpos flag
cout << 11 << end1;
This results in the following output:
+10
11

Many flags belong to groups, called format groups. A format group is a group of
flags that perform similar (sometimes mutually exclusive) formatting options. For
example, a format group named "basefield" contains the flags "oct", "dec", and "hex",
which controls the base of integral values. By default, the "dec" flag is set.
Consequently, if we do this:
cout.setf(ios: :hex) ; 1/ try to turn on hex output
cout «< 15 <« endl
We
get the following output:
15

Itdidn't work! The reason why is because setf() only turns flags on- it isn't smart
enough to turn mutually exclusive flags off. Consequently, when we turned ios:hex on,
10S::dec was still on, and ios::dec apparently takes precedence. There are two ways to get
around this problem.
st, we can turn off ios: :dec so that only ios::hex is set:
unsetf Cios: dec); // turn offdecimal output
Setf(ios: :hex) ;
// turn on hexadecimal output
152
Y Vipul'sM Object Oriented Programming

cout 15 << end1;


<<
víth
G,
Now we get output as expected:
f
The second way is to use a different form of setf() that takes two
parameterc..
parameter is the flag to set, and the second is the formatting group itit belongS
belongs lirs
using this form of setf(), all of the flags belonging to the group are rned off. to.When
turned oft,
the flag passed in is turned on. For example: . and only
//Turn on ios::hex as the only ios:: basefield flag
cout.setf(ios::hex, ios: :basefield);
cout << 15 << end1;
This al so produces the expected output:
F

Using setf() and unsetf() tends to be


awkward, so C++ provides a second wa
change the formatting options: manipulators. The way
they are smart enough to turn on and off the
nice thing about manipulators
Lt
isthat
appropriate flags. Here is an examni
using some manipulators to change the base:
Cout << hex << 15 <<
of
end1; // print 15 in hex
cout << 20 << end1;
cout << dec <« 25 <<
//we' re still in hex
end1; // back to decimal
This program produces the output:

14
25
Useful formatters:
Here is a list of some of the more
Flags live in the ios class, useful flags, manipulators, and
manipulators lives in the std namespace,member functions
functions live in the ostream class. and the member
Manipulator
Meaningg
showpos Prefixes positive numbers
with a +
no showpos Doesn't prefix positive numbers
Example: with a +
cout <<15 << end1;
cout.setf(ios::showpos);
cout «< 15 <« end1;
cout << noshowpos <<
15 << end1;
cout << showpos <«
15 << end1;
Result:
15
+15 1
15
+15 9

Manipulator
uppercase Meaning
Uses upper case
no uppercase letters
Uses lower case letters
inheritance
in C++, Pointers to objects, Input-output and Manipulators
1workingwith
in C++ Y"Y" 153

. Example:
678.9 <
123456
« :upperca
end1;
case);
co etf(ios:
12345678.9 < end1;
ana Co << 2345678.9<< endl;
cout noupoercase
cout uppercase << 123
12345678.9 << end1:
out
Result:
.23457e+007
1.23457E+007
1.23457e+007
1.23457E+007
Flag Meaninng
Group
Sis basefield dec Prints values in decimal (default)
basefield hex Prints values in hexadecimal
basefield Oct Prints values in octal

basefield (none) Prints values according to leading characters of value

Manipulator Meaning
dec Prints values in decimal

hex Prints values in hexadecimal


oct Prints values in octal
ICtiorE

embExample:
Cout 15 << end1;
cOut.setf(ios::decC, ios::basefiel1d);
Cout 15 << end1;
cOut.setf(ios::oct, ios::basefield);
cout < 15 << endl;
cout.setf(ios::hex, ios:: basefield);
cout < 15 << end1;
cout << dec << 15 << end1
cout << oct << 15 << endl1;
cout< hex << 15 << end1;
Result:
5

decimal points: with


the precision and format that
eCision, notation, and
Usir possible to change
whia manipulators (or flags), it is are several formatting
options
displayed. There
COmhi ng point numbers are ways, so we will take a closer look at this.
Somewhat complex
154 Vipul'sM Object Oriented Programming
with c
Group Flag Meaningg
floatficld fixed Uses decimal notation for floating-point numbers
floatfieldscientificUses scientific notation for floating-point numbers
floatficld (none) Uses fixed for numbers with few digits, scientific
floatfield otherrwise
showpoint | Always show a decimal point and trailing 0's for floatin.
oating-point
values
Manipulator
- Meaning
fixed Use decimal notation for values
scientific | Use
scientific notation for values
showpoint Show a decimal point and trailing 0's
for floating-point values
noshowpoint Don't show a decimal point and
trailing 0's for floating-point
sctprecision(int)| Sets the precision values
of floating-point numbers
(defined in iomanip.hl
Member function.
precision()
Meaning
Returns the current precision
precisionfint) of floating-point
Sets the precision numbers
of floating-point
Precision numbers and returns old
If fixed or scientific
in the fraction is
notation is used, precision
displayed. Note that determines how many
significant digits, if the precision decimal places
the number will be is less than
cout <« fixed <<
end1;
rounded. the number of
cout << setprecision(3)
<<
123.456
cout < setprecision(4) << end1;
<<
123.456
cout «< setprecision(5) « endl;
cout <« setprecision(6) << 123.456 << end1;
cout <« setprecision(7) << 123.456 <« end1;
cout <« scientific << 123.456 << end1;
<« endl;
cout <<
setprecision(3) <<
cout<« setprecision(4) 123.456 << end1;
cout<« setprecision(5) << 123.456 << end1;
cout<« setprecision << 123.456 <« endl;
cout (6)
<« setprecision(7) << 123.456 << endl;
Produces the < 123.456 << endl;
result:
123.456
123.4560
123.4560o
123.456000
123.4560000
1.235e+002
1.2346e+002
1.23456e+002
1.234560e+002
1.2345600e+002 2
Inheritan C++, Pointers to Objects, Input-Output
wiltn
and Manipulators in C++
working 155
summary table with some more examples:
Here'sa
Option Precision 12345.0
3 0.12345
1.23e+04
Normal 0.123
1.235e+004
0.1235
12345
0.12345
6 12345 0.12345
3 1.23e+004
Showpoint 0.123
4 1.235e+004
0.1235
5 |12345.
0.12345
6 12345.0 0.123450
3 12345.000
Fixea 0.123
|
12345.0000
0.1235
5 12345.00000
0.12345
6 12345.000000 0.123450o
Scientific 3 1.235e+004 1.235e-001
1.2345e+004 1.2345e-001
Dlac

Der
1.23450e-+004 1.23450e-001
1.234500e+004 1.234500e-001
Width, fill characters, and justification:
Typically when you print numbers, the numbers are printed without any regard to
the SDace around them. However, it is
possible to left or right justify the printing of
numbers. In order to do this, we have to first
define a field width, which defines the
number of output spaces a value will have. If
the actual number printed is smaller than
the field width, it will be left or right justified (as specified).
If the actual number is
largerthan the field width, it will not be
truncated --it will overflow the field.
Group Flag Meaning
2djustfield internal|Left-justifies the sign of the number, and
right-justifies the value
adjustfield
left |Left-justifies the sign and value
adjustfieldright
Right-justifies the sign and value (default)
33.4 Manipulators:
Manipulator
Meaning
nternal
Left-justifies the sign of the number, and right-justifies the value
eft
ight Left-justifies the sign and value
|Right-justifies the sign and value
156 vipul'sTM Object Oriented Prograrmming
witt c,
setfill(char) Sets the parameter as the fill fined
character (defined in
in iomani
iomanip.)
setw(int) Sets the field width for input and output to the parameta
in ionmanip.h) defined

Member function Meaning


fill() currentReturrns
fill character the
fill(char) Sets the
fill character and returns the old fill character
width0 Returns the current field width
width(int) Sets the current field width and returns old field widthh
In order to use any of these formatters, we first have to set a field wid th. Thie
done via the width(int) member cant
function, or the setw) manipulator.
justification is the default. Note tha+
cout << -12345 << end1;
right
// print default value
cout << setw C10) << -12345 <s end1; with no field ia.
cout << setw C10) << left << -12345
// print default with
<< endl; field idre
cout << setw (10) << right << -12345 << end1; // print 1eft justifig
cout<< setw(10)<< internal << -12345 // print right
<< end1; justifie
This produces the result: // print internal1y
-12345 justified
-123455
2345
-12345
12345
One thing to note is
They are not persistent that setw() and width() ornly affect
like some other the next output statement
Now, let's set a fill flags/manipulators.
character and do the same
cout.fil1C'* ');
cout<< -12345 << endl; example:
cout << setw(10) //print
<< -12345 << end1; default value with no field
cout width
<< setw(10) << left << -12345
// print
default with
<< endl; field width
cout << setw C10) << right // print left justified
<< -12345
<< end1;
cout << setw(10) << 7/ print
internal << right
-12345<< end1; justified
/7 print
internal1y justified
Inherita in C++, Pointers to Objects, Input-Output and Manipulators in C++ 157
with
Working
output:
duces the
produces
This
-12345
****-12345
-12345****
***-12345
***12345
states:
Stream several state
base class contains flags that are used to signal various
The iosthat,may occur wher using streams:
conditions that
Meaning
Flag
Goodbit Everything is okay
N
Some kind of fatal error occurred (eg. the program tried read past the end
badbit
of a file)
The stream has reached the end of a file
eofbit
A non-fatal error occurred (eg. the user entered letters when the program
failbit
was expecting an integer)
t AIthough these flags live in ios_base, because ios is derived from ios_base and ios
kes less
typing than ios_base, they are generally accessed through ios (eg. as
tir hd-ioS::failbit).iosbase also provides a number of member functions in order to
states:
rtconveniently access these
Member Function Meanin
good() Returns true if the goodbit is set (the stream is ok)
bad0 Returns true if the badbit is set (a fatal error occurred)
eof() Returns true if the eofbit is set (the stream is at the end of a file)
fail() Returns true if the failbit is set (a non-fatal error occurred)
clear() Clears all flags and restores the stream to the goodbit state
clear(state) Clears all flags and sets the state flag passed in
rdstate() Returns the currently set flags
setstate(state) Sets the state flag passed in

Question Bank for Self-Practice

(0 What does inheritance mean in C++?


( Explain different forms of inheritance.
When do we publicly derive a class?
What is a virtual base class? is created?
nat order the constructors are called when a derived class object
) are the differences between composition and inheritance?
a
158 Vipul'sM Object Oriented Programmings
mming
with
and private members?
C
(7)VVhat iS the difference between protected
X8) What are the different forms of inheritance? Give an example for each.
(9) When do we use protected visibility specifier to a class member?
(10) What is an abstract class? Explain
(11) What is vitual destructor? E>xplain.
(12) Explain the flags in ios_bag class?
(13) What are manipulators? Why are they used?
Explainthe syntax of write) and read() function?
4
(75) How costructor and destructors are called
in inheritance?

You might also like