0 ratings0% found this document useful (0 votes) 35 views18 pagesOops Ut02 QB Ans.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
es fT
aS ee ee
ing Ansa
Qs cagswen ane
Dennwles Q's 1 1,2, 34.5:6
YW pang RS OSs 3456,
Aly the best J~~ ~sseau Cass and the exist .
existing class is known as the base class or parent
L class.
faa] INTRODUCTION TO INHERITANCE
, {Inheritance is a form of software reusability
: : 'y ut i
‘absorbing their attributes and behavior.’ ty i which new classes are created from existing classes Py
[fhe technique of building new classes
incorporating the properties of existing classes
~
{
is known as inheritance. \
Inheritance is a process by which object of one
Base class
Poeaves? LIS gives us different forms of
inheritance as explained below:
—: Single Inheritance:
rent forms of Derived class
Fig, 3.2: Example of Inheritance
A derived class with only one base class is called single inheritance, (See
Fig. 3.3 (a)),
2. Multiple Inheritance: A derived class with more than one base class is called multiple
inheritance, (See Fig. 3.3 (b)).
sa Hierarchical Inheritance: If one base class is inherited by more than one derived classes, it is
called hierarchical inheritance, (See Fig. 3.3 (c)).
a Multilevel Inheritance: The mechanism of deriving a class from another ‘derived class' is known
oo
as multilevel inheritance, (See Fig. 3.3 (d)).
Hybrid Inheritance: One class is inherited by many derived classes which are again base class
for other derived classes. This form of inheritance is called hybrid inheritance. In other words,
combination of one or more inheritance together is called as hybrid inheritance, (See Fig. 3.3 (e)),
Fe aieee ae ees to ~~ concept of dynamic binding, ised gy I
. ar ate Bidet to haa of actual code to a function call. There are two types of bindings
: § (early binding) and dynamic binding (late binding). In this chapter we study
the concepts of pointers, polymorphism and virtual function in detail.
a1 |_ CONCEPTS OF POINTER
. te
feference. A pointer is a variable which can holds the memory address of another variable. |
+ Itis very similar to normal variable and it also has to be defined before using it to hold the address.
Each type pointer variable can hold memory address of that data type variable only. A pointer is a
variable whose value is the address ofanother variable.
* Pointer plays an important role in C++ with following advantages: (eel
tured variables from functions.
14. Apointer allows to return struct '
2 aes improves the efficiency of youtines in some complex data structures such as linked list,
ataclen eaniac ett.
_--4 wriehont nhvsically moving them.Jutpur:
Enter Roll No:1
Enter Marks
Part1:4e0
Part2:450
Enter Sports Score:25
Roll No:1
Marks Obtained
Part1:400
Part2:450
Sports Score is:25
.Jotal Score:875
| 3.3.2 | Abstract Classes s [W-23]
. YAclass that contains at least one pure virtual function is said to be abstract. A pure virtual function is
‘a member function i.e:, declared in an abstract class, but defined in a derived clas: cs
e An abstract class does not create any object and it contains one or more functions for which there is
no definitions (i.e., a pure virtual function).
stract class. An abs; i i
2 only to act as base class, ie. to be inherited by other classes, It is a desi, nee one seen
development and provides a base upon which other classes are built Be: concept In Program
ans. irtual function is called an Db: i
ss containing a pure vir es abstract class, It ;
a Bere define objects of a class containing a pure virtual functio: tts called
Sebning classes which are derived from it.
le an create pointers and references to an abstract
We of me poll morphism, which depends upon base-c]
run
virtual function.er evedOoject; // point to DerivedCias® SVlr’"
P->setx(g9); // access DerivedClass object
derivedobject. sety(a8); // can't use p to set y, so do it direct]
cout << "\nDerived object x: " << p->getx();
cout << "\nDerived object y: " << derivedobject.gety()3
return 9;
}
Output:
Base object x: 10
Derived object x: 99
Derived object y: sg
° [Polymorphism is a Greek term that consists of two words, poly and morph. Poly means many and
morph means forms. So, polymorphism means ‘one name many forms’. |
Polymorphism is the process of defining a number of objects at different classes into group and call
the method to carry out the operation of the objects using different function calls.
[ 4.3.1 | Types of Polymorphism
e There are two types of polymorphism as explained belo’
1. Compile-time Polymorphism: eERED
When the required information to-call a function is known to the compiler at the compile-time, it is
known as compile-ttme polymorphism, early binding, or static binding.
° The process of linking a particular call statement with a.particular definition is called as binding.
Early binding is the bindfhg that an object is bound to its function call at compile-time.
Early binding is implemented using operator overloading and function overloading. The main
° advantage of early binding is efficiency and disadvantage is the lack of flexibility.
un-time Polymorphism: a ;
2, R information to call a function is known to the compiler at the execution time or
e required 4 now piler at
i whe a it i Finoyin as run-time polymorphism, late binding, or dynamic binding.
run-time, itis ae Ne Races hie edna theta el a eg ge BN Oey lO OF bes tepe Ne ee
ona ee
SKS. bellboy epdglla uGemlmesba
Pat tis dine abt tee
[Compile Bicne pelemaa Roy aljense tela
earhpod a sAe
Bom ved A ie binding
siete. y a
ate Ax ; i
id programming Using C++ 53
orient
input system of C++
¥ re ” has a group of classes that defines all the file handling fun
ig ¢stream: FOC handling input files.
if ofstream: For handling output files.
({ fstrean: For handling files on which both input and output can be performed.
s declare as a class ifstream. It is derived from istream. Output stream is declared as a
o fstream class. It is
put/Output stream should belongs t
' ppput stream
s derived from ostream. In
class ofstream. It i
derived from jostream.
ns with the files ar
+ The operatio!
Fig.5.3. The hierarchy of C++ file strea
=
e mainly read and write. C++ provides various classes as shown in
m classes is shown in Fig. 5.3.
pointer
iostream.h
file.
e help of virtual
«C++ supports run-time polymorphism with th :
lected dynamically
- binding because the appropriate function is sel
[45.1 Virtual Functions
irtual means to appear like something while in reality it is s
Member function that is declared within a base class and redefin
The virtual functions implement the “one interface, multiple met
polymorphism. A virtual function is a function in a base class tha
‘virtual’ keyword before the function declaration
irtual function is a
J
that underlies
the keyword
‘omething else. A wi
ed by a derived clas:
thods" philosophy
t is declared using
‘virtual’,
Syntax, to make a function virtual, just precede the
in the base class.
class user_defined_name
{
private:
public:
virtual return_type function_name1 (argument)
virtual return_type function_name2 (argument)
virtual return_type function_namen (argument)
b
ae virtual void show(); //show function is virtual
virtual functions access normally, it behaves just lik i
However. virtual function te nesd cn oust ake any other type nr 7"WS Ubject
Enter the 1
Feet :5
inches:17
Enter the nui
The multipli
ength
mber which is to be multiplied with object5
ed object :
Feet :29
inches:7
[4.4.5 | Rules for Operator Overloading 2g
° eee it looks simply to redefine the operators, there are certain restrictions and/or Htaton
in
Overloading them. Some of them are listed below:
a. Only existing operators can be overloaded. New operators cannot be created.
2. The overloaded operator must have at least one operand that is of user-defined type.
3 We cannot change the basic meaning of an operator. That is we cannot redefine the plus (+)
Operator to subtract one value from the other.
4- Overloaded operators follow the syntax rules of the original operators that cannot be overridden,
5. There are some operators that cannot be overloaded such as, *, :: etc. é
6. Unary operators, overloaded by means of a member function, take no explicit arguments and
return no explicit values, But those overloaded by means of a friend function take one reference
argument.Pointers and Polymorphism inc,
lect Oriented Programming Using c+,
| 4.5 | RUN-TIME POLYMORPHISM fons. It is called late or dynam,
9.3 °C supports runtime Polymorphism with the help of virtual functions.
\ ~binding be
, -time.
cause the appropriate function is selected dynamically at run
45.2] vi
rtual Functions A virtual function is g
to appear like something while in reality it is somethin ee class._{
on that is declared within a base class and redefined by a " philosophy that underlies
-*~ The virtual functions implement the “one interface, multiple methods flared using the keyworg
Polymorphism. A virtual function is a function in a base class that is dec
‘virtual’.
*~ Syntax, to make a functi
in the base class,
class user_defined_name
t
4.28
Virtual means
Member functi
a“ on virtual, just precede the ‘virtual’ keyword before the function declaration
private:
public:
virtual return_type function_name1 (argument)
virtual return_type function_name2 (argument )
virtual return_type function_namen (argument)
33 fgtihe ues
Example: virtual void show(); //show function is virtual.
, ; ally, it behaves just like any other
en virtual functions access norm. 5 ‘ype of class ea
Sener virtual function is used to support runtime Polymorphism wi. Member fiin-:
ie cai gt ee eh ee ag, oa iE a We s
°prrgasprey\7s
ff access derived, Funeti
p= 8425 // point to derived2 ”
p>display(); // access derived2 functi
return 3 :
}
qutput:
this is base virtual function
this is derived1 virtual function
this_is derived2 virtual function
(45.2 | Rules for Virtual Functions
7 The rules for virtual functions are listed below:
3.
1. The virtual function must be member of same class.
2
4,
Virtual functions are accessed by using object pointers. :
They cannot be static members i.e. must be non-static members.
The prototype of the base class version of a virtual function and all the derived class versions
must be identical.
5. We can have virtual destructors but do not virtual constructors.
We cannot use a pointer to a derived class to access object
of the base type ie. reverse is not true.
Ifa virtual function is defined in the base class, it need no
class.
t be necessarily redefined in the derived
8. A-virtual function can be a friend of another class.
| 45.3 | Pure Virtual Function
; i ly,
Most of the times, the virtual function inside the base class is rarely,
only serves as a placeholder. Such a function is caller
functions.
used for performing any a
d ‘do-noting functions’ which are pure
cap 20 after the closins
ing it with =0 2
~ A member function can also be made “pure virtual” by appending
to add theete) fi,
derived class, “mines/specifies how the elements of the base class are inherited by the
e visibility mode cai i i
on ity modes are Cas ae rhe n® oF Public or protected as explained below. All these three
class will be public or private on Ror Mode decides whether the inherited features of base
rae resto embers of the derived class.
1 Bin tht ane ee If the visibility mode is public, then the public members of base class will
& aera ction and the protected members will become part of the protected section of
the der ve lass, Recall that private members of the base class cannot be inherited.
2, Private Visibility Mode: If the Visibility mode is written as private then all public and protected
members of base Class will become private members of the derived class.
%. Protected Visibility Mode: If the visih: lity mode is protected then all members inherited will be
protected members of the derived class,
members.
The mechanism of deriving a new class from an old one is called inheritance or derivation. The old
class is referred'to as base class and the new class is called the derived class.
We can summarize the different access types according to - who can access them in the following
ccess E Protected = |" private.
1 Same class Yes Yes
Derived classes Yes No
No No
2,
UL 3. Outside classes1. Order of Calling Constructors:
tain constructors, thel
square?
yutput: i
Enter length to calculate the area ; ‘7
Area of square: 16 a circle?
culate the are? °
Enter radius to ca
Area of circle: 78-5
tance is involved p
ed? Second, howe
n
en inheril
nections Ca’
+ There are two major question
struct} 7 rn
when are base-class and derived class cons! ns? 3 derived class need not haye
punctio!
tor f ment, th ne or more arguments then te
onstrucl
parameters be passed to base-class © many are
+ As long as no base class constructor ares f constructor wilments ro ee base class construc,
co! | If a base class conta? ass in order to initializ
nstructor function. pnstructr P “ae the class © dat
mandatory for a derived class to have @ 60 eoared inside TBE” Sos, Every class has its om
© When a class is declared, a constructor is ost cuotor for MOTE
members. It is not possible to use a sing sf ie denivea
i imil the class. e a construt . Class,
constructor with a similar name aie class, it is possible t defini alized. It is not essential to decan
© When a class is derived from ano cis ses can be i sak lis base Clasg
and the data members of both base and derived aS" erived class WO 5 Such
the constructor of or constructors.
in the derived class or comm<
a constructor in a base class. Thus,
constructors are called constructors i
n base constructor is executed firs,
© When both the derived and base classes con’ i
is ‘i is executed. F
and then the constructor is the derived class is fedin the order in which thy
«Incase of multiple and multilevel inheritance, base classes ar° constru
appear in the declaration of derived class.
2. Passing Parameter to Base Class Constructor:
= Incase where derived class constructor requires one or more parameters, We simply use standard
parameterized syntax. However, how do we pass arguments to a constructor in a base class?
+ The constructor of the derived class receives the entire list of arguments with their values and passes
them to base constructor.
© The syntax of derived class constructor is given below:
derived constructor (argi, arg2,
bette arg(D)):
basel (argl),
base2(arg2),
basen(argn) ib
© In above syntax, basel through bas 5
en are the names
A colon separates the deri
ved class constructor dedlarauy base class
class specifications are separated fro es inheri
- m es io1 inherit i 8.
In case of multiple base classes arg, poe other by commay from base class ted by derived dls
to the base constructor and arg(p) eo’ "2°80 repr s. Specification and bas?
number of derived class. Provides the esents the
Para actu;
Meters that a Parameters that are passed
Ne Necessary to initializeUT TO pruyianr
data output data inp! prog!
Fig. 5.2; Iustration of File Input and Output Streams
5.1| STREAM CLASSES AND CLASSES FOR FILE STREAM OPERATIONS
e The file-handling techniques of C++ support file manipulation in the form of stream objects. The
stream object cin and cout are used extensively to deal with the standard input and output devices.
e The C++ input-output system support a hierarchy of classes that are used to manipulate both the
console and disk files, called stream classes.
(ceaming Using C++
output system of C+ has a group of ¢,
a
in? : lassi m
e es are! es that defi
ass . lefines all
' occa For handling input files, the Mite Pendle
“Ly prea For handling output files.
fer or handling files on whi ;
(ss ae : | which both input and output ean b
mr js declare as a class ifstream. It is derived from n be performed.
istream.
eal
jut _ It is derived from ostre uy
: wes crea ee am. Input/Output stream should b put stream is declared as a
od 10 ene fl longs to {stream class. It is
paved f°. with the files are mai
ae orion Wa eco fl ainly read and write. C++ provid
fis tne hierarchy 0 je stream classes isshowninfig.33. classes as shown in
rig pointer” °
+[[sveambut
oan ostream jeorooms fle
f
soa. Eel E
tse Toteweami| [Eitieput
“Bireamh fe
jierarchy of File Stream Classes in C++
‘and fatream are designed exclusively to manage the disk files and
header file fstream.h. To use these classes, include the following
Fig. 5.
| ne dasses ifstream, ofstreamy
ther declaration exists in te
satement is used in the PrOgraMy
#includesfstream. h>
«cue views each file as a sequence of Bytes:
specific byte number. For file processing ios
Prread (ifstream) and write (ofstream)-
«+ The functionalities of istream, ostream and ios
respectively. Details of file stream classes are given in the following table:
Each file ends either, with an end of file marker or at 2
tream.h and fstream.h must be included. fstream is used
stream are inherited to ifstream, ofstream and-fstream
fciass | me “) Deseription :
fiebut t's purpose is to set the file buffers to read and write. Contains close and ‘opend) as its
members.
Bteambase | It is the base class of fstream, ifstream ‘and ofstream classes. Contains close and open0
functions.
isveam [it provides input operations. Contains open with default input mode. Inherits the
eS functions getO, getline, read0, seekg0 and tells from istream.
am | It provides output operations. Contains openO with default output
put0, seekpO, tellp0 and writeO from ostream.
steam (0 with default input
Teallows simultaneous input and output operations. Contains open ;
mode. Inherits all the functions from istream. and ostream classes through iostream.
mode. Inherits
_F322 | Multilevel Inheritance
is derived by a child class
Enter Employes ©"
ter Sex: ™m
eee basic salary : 50000
Enter name = virat
enter Employee id : 2
Enter Sex. : ™
salary : 40000
50000
Enter basic
Name Empno. Sex Bsalary ey ees
ame =mahi Emp 0+ is =1 Sex=m Basic alary =
ae is =2_Sex=m Basic Salary = 40000
name =virat Emp N0-
ed by another child class, then itis
which further deriv
When a base class
known as multilevel inheritance.
Syntax of ‘multilevel inheritance is given below:
e_class_name
Intermediate
base class
class bas:
{
properties;
methods;
Fig. 3.9: Multilevel Inheritance
ub
es intermediate_class_name:visibility_mode base_class_name
properties;
methods; :
af
fo child_class_name:visibility_mode intermediate_class_name
properties;
methods;
3
The class which provides li
les link between i i
two classes is known as intermediate base class. This ®
illustrated in Fig. 3.9,