0% found this document useful (0 votes)
87 views

C++ Unit 2

The document discusses key concepts of OOP with C++ including inheritance, polymorphism, and I/O and file management. It covers inheritance types like single, multiple, and multilevel inheritance. It describes pointers in C++ and implementing polymorphism using virtual functions. It also discusses C++ stream classes for unformatted and formatted I/O, file streams, and file management functions for working with binary and text files.

Uploaded by

Orlin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views

C++ Unit 2

The document discusses key concepts of OOP with C++ including inheritance, polymorphism, and I/O and file management. It covers inheritance types like single, multiple, and multilevel inheritance. It describes pointers in C++ and implementing polymorphism using virtual functions. It also discusses C++ stream classes for unformatted and formatted I/O, file streams, and file management functions for working with binary and text files.

Uploaded by

Orlin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

OOP with C++

Unit II
Inheritance : Concept of Inheritance, types of inheritance: single, multiple,
multilevel, hierarchical, hybrid, protected members, overriding, virtual base
class.
Polymorphism : Pointers in C++, Pointers and Objects, this pointer, virtual
and pure virtual functions, Implementing polymorphism.
I/O and File management : Concept of streams, cin and cout objects, C++
stream classes, Unformatted and formatted I/O, manipulators, File stream,
C++ File stream classes, File management functions, File modes, Binary and
1
random files. 16 Hrs
Inheritance
 The mechanism of deriving new class from an old one is called
“inheritance”
 The old class is referred to as the base class and the new one is
called the derived class or sub-class
 Syntax:
class derived_class_name: visibility_mode base_class_name
{
//Members of derived class
}

2
Forms of inheritance:
1. Single inheritance
2. Multiple inheritance
3. Hierarchical inheritance
4. Multi-level inheritance
5. Hybrid inheritance

3
Visibility of inherited members

Base class Derived class visibility


visibility
Public derivation Private Protected
derivation derivation
Private Not inherited Not inherited Not inherited

Protected Protected Private Protected

Public Public Private Protected

4
1. Single inheritance

5
2. Multiple inheritance

6
3. Hierarchical inheritance

7
4. Multi-level inheritance

8
5. Hybrid inheritance

9
Virtual base class
When two or more objects are derived from a common base
class, Multiple copies of the base class being present in an
object derived from those objects can be prevented by declaring
the base class as virtual when it is being inherited. Such a base
class is known as virtual base class.

10
Inheritance and constructor
 Base class constructors are always called in the derived class
constructors.
 Whenever derived class object is created, first the base class default
constructor is executed and then the derived class's constructor
finishes execution.
 Whether derived class's default constructor is called or parameterised
is called, base class's default constructor is always called inside them.
 To call base class's parameterised constructor inside derived class's
parameterised constructor, it must be explicitly mentioned while
declaring derived class's parameterized constructor.
 The parameterised constructor of base class cannot be called in
default constructor of sub class, it should be called in the
11
parameterised constructor of sub class.
Characteristics of constructor
 They should be declared in the public section.
 They are invoked automatically when the objects are
created.
 They do not have return (data type) type not even
void and there for they cannot return any values.
 They can not be inherited, the a derived class can call
the base class constructor.
 They make implicit calls to the operator new and
delete when memory allocation is required.
12
 Example: Constructor_inher_1.cpp
Constructor_mul_inh.cpp
Constructor_para_inher.cpp

13
Order of constructor and Destructor call for a given order
of Inheritance:

14
C++ Pointers
 C++ pointers are easy and fun to learn.
 Some C++ tasks are performed more easily with
pointers.
 Other C++ tasks, such as dynamic memory
allocation, cannot be performed without them.
 Every variable has a memory location and every
memory location has its address defined which can be
accessed using ampersand (&) operator which denotes
an address in memory.
 Example: ampersand.cpp
15
What Are Pointers?
 A pointer is a variable whose value is the address of another
variable.
 Like any variable or constant, you must declare a pointer before
you can work with it.
 The general form of a pointer variable declaration is:
type *var-name;
 Here, type is the pointer's base type; it must be a valid C++
type and var-name is the name of the pointer variable.
 The asterisk you used to declare a pointer is the same asterisk
that you use for multiplication.
 However, in this statement the asterisk is being used to
16
designate a variable as a pointer.
Continued…
 Following are the valid pointer declaration:
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
 The actual data type of the value of all pointers, whether
integer, float, character, or otherwise, is the same, a long
hexadecimal number that represents a memory address.
 The only difference between pointers of different data types
is the data type of the variable or constant that the pointer
points to.
17
Using Pointers in C++:
 There are few important operations, which we will
do with the pointers very frequently.
a) we define a pointer variables
b) assign the address of a variable to a pointer and
c) finally access the value at the address available in the
pointer variable.
 This is done by using unary operator * that returns
the value of the variable located at the address
specified by its operand.
 Example: pointer.cpp
18
C++ Pointers in Detail:

19
C++ NULL pointers
 It is always a good practice to assign the pointer NULL
to a pointer variable in case you do not have exact
address to be assigned.
 This is done at the time of variable declaration.
 A pointer that is assigned NULL is called a null pointer.
 The NULL pointer is a constant with a value of zero
defined in several standard libraries, including iostream.
 If a pointer contains the null (zero) value, it is assumed
to point to nothing.
 Example: null_pointer.cpp
20
new and delete operators in C++ for
dynamic memory
The new operator
 The new operator requests for the memory allocation in
heap.
 If the sufficient memory is available, it initializes the memory
to the pointer variable and returns its address.
 Here is the syntax of new operator in C++ language,
 pointer_variable = new datatype;
 Here is the syntax to initialize the memory,
 pointer_variable = new datatype(value);
 Here is the syntax to allocate a block of memory,
 pointer_variable = new datatype[size];
21
The delete operator
 The delete operator is used to deallocate the memory.
 User has privilege to deallocate the created pointer variable
by this delete operator.
 Here is the syntax of delete operator in C++ language,
 delete pointer_variable;
 Here is the syntax to delete the block of allocated memory,
 delete[ ] pointer_variable;

 Example: new.cpp

22
C++ pointer arithmetic
 We can perform arithmetic operations on a pointer just as
we can a numeric value.
 There are four arithmetic operators that can be used on
pointers: ++, --, +, and –

Incrementing a Pointer:
 We prefer using a pointer in our program instead of an
array because the variable pointer can be incremented,
unlike the array name which cannot be incremented
because it is a constant pointer.
 Example: ptr_arith_inc.cpp
23
Continued…
Decrementing a Pointer:
 The same considerations apply to decrementing a pointer,
which decreases its value by the number of bytes of its data
type.
 Example: ptr_arith_dec.cpp

Pointer Comparisons
 Pointers may be compared by using relational operators,
such as ==, <, and >. If p1 and p2 point to variables that are
related to each other, such as elements of the same array,
then p1 and p2 can be meaningfully compared.
24 Example: ptr_comparison.cpp
C++ array of pointers
 There may be a situation, when we want to maintain an array,
which can store pointers to an int or char or any other data
type available.
 Following is the declaration of an array of pointers to an
integer:
int *ptr[MAX];
 This declares ptr as an array of MAX integer pointers. Thus,
each element in ptr, now holds a pointer to an int value.
Example:
array_of_ptr.cpp

25
Pointer to objects:
 A pointer to a C++ class is done exactly the same way as a
pointer to a structure and to access members of a pointer to a
class, use the member access operator ->.
 Also as with all pointers, it must initialize the pointer before
using it.
 Example: Pointer_objects_1.cpp
Array_pointer_objects.cpp

26
This pointer
 This pointer is a pointer that points to the object for which this
function is called.
 Example: this_pointer.cpp

27
Polymorphism
 The word polymorphism means having many forms.
 Typically, polymorphism occurs when there is a hierarchy of classes
and they are related by inheritance.
 “C++ polymorphism means that a call to a member function
will cause a different function to be executed depending on the type
of object that invokes the function”
 Achieving Polymorphism
1. Compile time polymorphism
2. Run time polymorphism
 Example: polymorphism.cpp
 Example: pure_virtual.cpp

28
29
Managing console input /output operations
 C++ supports two complete I/O systems: the one inherited from
C and the object-oriented I/O system defined by C++
 Every program takes some data as input and generates processed
data as output following the input-process-output cycle
 C++ supports all of C’s rich set of I/O functions that can be used
in the C++ programs
 But these are restrained from using due to two reasons
i. First I/O methods in C++ supports the concept of OOP
ii. Secondly I/O methods in C can not handle the user defined
data types such as class objects
 C++ uses the concept of streams and stream classes to implement
its I/O operation with the console and disk files
30
C++ streams:
 A stream act like a source or destination
 The source stream that provide data to the program is called
the input stream and the destination stream that receive
output from the program is called the output stream.
 C++ contains cin and cout predefined streams that opens
automatically when a program begins its execution.
 cin represents the input stream connected to the standard
input device
 cout represents the output stream connected to standard
output device.

31
C++ Stream Classes:
 The C++ I/O system contains a hierarchy of classes that are
used to define various streams to deal with both the console
and disk files.
 These classes are called stream classes.
 These classes are declared in the header file iostrem.
 The file should be included in all programs that communicate
with the console unit.

32
Stream classes for console I/O operations
33
34 Stream classes for console operations
Unformatted input/output Operations:
Overloaded operators >> and<<
 Objects cin and cout are used for input and output of data by
using the overloading of >> and << operators.
 The >> operator is overloaded in the istream class and << is
overloaded in the ostream class.
 The following is the format for reading data from keyboard:
cin>>variable1>>variable2>>…………..>>variable n
 where variable 1 to variable n are valid C++ variable names
that have declared already.
 This statement will cause the computer to stop the execution
and look for the input data from the keyboard.
 The input data for this statement would be
35 data1 data2…………..data n
put() and get() functions:-
 The classes istream and ostream define two member functions
get(),put() respectively to handle the single character
input/output operations.
 There are two types of get() functions.
 Both get(char *) and get(void) prototype can be used to fetch a
character including the blank space, tab and newline
character.
 The get(char *) version assigns the input character to its
argument and the get(void) version returns the input character.
 Since these functions are members of input/output Stream
classes, these must be invoked using appropriate objects.
 The function put(), a member of ostream class can be used to
output a line of text, character by character.

36 Example: put_get.cpp
getline() and write() functions:
 A line of text can be read or display effectively using the line
oriented input/output functions getline() and write().
 The getline() function reads a whole line of text that ends with a
newline character.
 This function can be invoked by using the object cin as follows:
cin.getline(line,size);
 This function call invokes the function getline() which reads
character input into the variable line.
 The reading is terminated as soon as either the newline character
‘\n’ is encountered or size-1 characters are read(whichever occurs
first).
 The newline character is read but not saved, instead it is replaced by
the null character.
 Example: get_line.cpp
37
Continued…
 The write() function displays an entire line and has the
following form:
cout.write(line,size)
 The first argument line represents the name of the string to be
displayed and the second argument size indicates the number
of characters to display.
 It does not stop displaying characters automatically when the
null character is encountered.
 If the size is greater than the length of line, then it displays
beyond the bound of line.
 Example: write.cpp
38
Formatted Console I/O Operations:-
 C++ supports a number of features that could be used for
formatting the output.
 These features include:
➢ios class function and flags.
➢manipulators.
➢User-defined output functions.
 The ios class contains a large number of member functions
that would help us to format the output in a number of ways.
 The most import any ones among them are listed in table

39
ios format functions
Function Task
width() To specify the required field size for displaying an output
value
precision() To specify the number of digits to be displayed after the
decimal point of float value
fill() To specify a character that is used to fill the unused portion
of a field
setf() To specify format flags that can control the form of output
display(such as left-justification and right-justification)
unsetf() To clear the flags specified

40
Manipulators
 “Manipulators are special functions that can be included in the
I/O statements to alter the format parameter of stream”
 Table shows some important manipulator functions.
 To access these manipulators, the file iomanip should be included
in the program.

41
Defining Field Width: width()
 The width() function is used to define the width of a field
necessary for the output of an item.
 As it is a member function, object is required to invoke it like
cout.width(w);
 here ‘w’ is the field width.
 The output will be printed in a field of w character wide at
the right end of field.
 The width() function can specify the field width for only one
item(the item that follows immediately).
 After printing one item(as per the specification) it will revert
back the default.

42 Example: width.cpp
Setting Precision: precision():
 By default ,the floating numbers are printed with six digits
after the decimal points.
 However ,we can specify the number of digits to be displayed
after the decimal point while printing the floating point
numbers.
 This can be done by using the precision () member function as
follows:
cout.precision(d);
 where d is the number of digits to the right of decimal point.
 Unlike the function width(),precision() retains the setting in
effect until it is reset.
 Example: precision.cpp
43
FILLING AND PADDING :fill()
 The unused portion of field width are filled with white spaces,
by default.
 The fill() function can be used to fill the unused positions by any
desired character.
 It is used in the following form:
cout.fill(ch);
 Where ch represents the character which is used for filling the
unused positions.
 Financial institutions and banks use this kind of padding while
printing cheques so that no one can change the amount easily.
 Example: fill.cpp
44
FORMATTING FLAGS, Bit Fields and setf():
 The setf() a member function of the ios class, can provide
answers left justified.
 The setf() function can be used as follows:
cout.setf(arg1.arg2);
 The arg1 is one of the formatting flags defined in the class ios.
 The formatting flag specifies the format action required for the
output.
 Another ios constant,arg2,known as bit field specifies the group
to which the formatting flag belongs.
 Example: flags_in_setf.cpp

45
Managing Output with Manipulators:
 The header file iomanip provides a set of functions called
manipulators which can be used to manipulate the output
format.
 They provide the same features as that of the ios member
functions and flags.
 Two or more manipulators can be used as a chain in one
statement as follows
cout<<manip1<<manip2<<manip3<<item;
cout<<manip1<<item1<<manip2<<item2;
 This kind of concatenation is useful when we want to display
several columns of output.

46 Example: Manip.cpp
The most commonly used manipulators are shown below

47
Designing our own manipulators:
 The general form for creating a manipulator without any
argument is
ostream & manipulator (ostream & output)
{
……………
…………….(code)
……………..
return output;
}
 Example: User_defined_manip.cpp

48
Working with C++ files
Introduction :
 When a large amount of data is to be handled in such situations
floppy disk or hard disk are needed to store the data.
 The data is stored in these devices using the concept of files.
 “A file is a collection of related data stored in a particular area
on a disk”
 Programs can be designed to perform the read and write
operations on these files.
 The I/O system of C++ handles file operations which are very
much similar to the console input and output operations.
 It uses file streams as an interface between the programs and
49 files.
Figure: File Input and output stream
50
Continued…
 The stream that supplies data to the program is called input
stream and the one that receives data from the program is
called output stream.
 In other words input stream extracts data from the file and
output stream inserts data to the file.
 The input operation involves the creation of an input stream
and linking it with the program and input file.
 Similarly, the output operation involves establishing an output
stream with the necessary links with the program and output
file.

51
File Stream Classes:
 The I/O system of C++ contains a set of classes that defines the
file handling methods. These include ifstream, ofstream and
fstream.
 These classes are derived from fstreambase and form the
corresponding iostream class.
 These classes ,designed to manage the disk files are declared in
fstream and therefore this file is included in any program that
uses files.
 For using a disk file the following things are necessary
1. Suitable name of file
2. Data type and structure
3. Purpose
52 4. Opening Method
Figure: Stream classes for file operations

53
54
Opening and closing a file
 The filename is a string of characters that makeup a valid filename
for the operating system.
 It may contain two parts ,primary name and optional period with
extension.
 Examples are Input.data, Test.doc etc. For opening a file firstly a file
stream is created and then it is linked to the filename.
 A file stream can be defined using the classes ifstream, ofstream and
fstream that contained in the header file fstream.
 The class to be used depends upon the purpose whether the write
data or read data operation is to be performed on the file.
 A file can be opened in two ways:
(a) Using the constructor function of class.
55 (b) Using the member function open() of the class.
Opening Files using Constructor:
 While using constructor for opening files, filename is used to
initialize the file stream object.
This involves the following steps
(i) Create a file stream object to manage the stream using the
appropriate class
i.e the class ofstream is used to create the output stream and
the class ifstream to create the input stream.
(ii) Initialize the file object using desired file name.
 Example: Open_file_constructor.cpp

56
Opening Files using open()
 The function open() can be used to open multiple files that
uses the same stream object.
 For example to process a set of files sequentially, in such case a
single stream object can be created and can be used to open
each file in turn.
 This can be done as follows:
File_stream_class stream_object;
Stream_object.open (“filename”);
 Example: Open_multiple.cpp

57
Finding End of File:
 While reading a data from a file, it is necessary to find where the
file ends i.e end of file.
 The programmer cannot predict the end of file, if the program
does not detect end of file, the program drops in an infinite loop.
 To avoid this, it is necessary to provide correct instruction to the
program that detects the end of file.
 Thus when end of file of file is detected, the process of reading
data can be easily terminated.
 An ifstream object such as fin returns a value of 0 if any
error occurs in the file operation including the end-of –file
condition.
 Thus the while loop terminates when fin returns a value of zero
58
on reaching the end-of-file condition.
Continued…
 There is an another approach to detect the end of file
condition.
 The statement
if(fin1.eof() !=0 )
{
exit(1);
}
 returns a non zero value if end of file condition is
encountered and zero otherwise.
 Therefore the above statement terminates the program on
reaching the end of file.
59
File Opening Modes:
 The ifstream and ofstream constructors and the function open() are
used to open the files.
 Up to now a single arguments is used that is filename.
 However, these functions can take two arguments, the second one
for specifying the file mode.
 The general form of function open() with two arguments is:
stream-object.open(“filename”,mode);
 The second argument mode specifies the purpose for which the file
is opened.
 The prototype of these class member functions contain default values
for second argument and therefore they use the default values in the
absence of actual values.
 The default values are as follows :
ios::in for ifstream functions meaning open for reading only.
60 ios::out for ofstream functions meaning open for writing only.
File Mode Operation
61
Sequential Input and Output Operations:

 The file stream classes support a number of member


functions for performing the input and output
operations on files.
 One pairs of functions, put() and get() are designed
for handling a single character at a time.
 Another pair of functions, write(),read() are
designed to write and read blocks of binary data.

62
put() and get() Functions:
 The function put() writes a single character to the associated
stream.
 Similarly, the function get() reads a single character from the
associated stream.
 The following program illustrates how the functions work on a
file.
 The program requests for a string, on receiving the string,the
program writes it, character by character, to the file using the
put() function in a for loop.
 The length of string is used to terminate the for loop.
 Example: put_get_file.cpp
63
write() and read () functions:
 The functions write() and read(),unlike the functions put() and
get() handle the data in binary form.
 This means that the values are stored in the disk file in same
format in which they are stored in the internal memory.
 An int character takes two bytes to store its value in the binary
form, irrespective of its size.
 But a 4 digit int will take four bytes to store it in the character
form.
 The binary input and output functions takes the following form:
infile.read (( char * ) & V, sizeof (V));
outfile.write (( char *) & V, sizeof (V));
 Example: Binary.cpp
64
Error Handling during File Operations:
 There are many problems encountered while dealing with files
like
➢ a file which we are attempting to open for reading does not
exist.
➢ The file name used for a new file may already exist.
➢ We are attempting an invalid operation such as reading past the
end of file.
➢ There may not be any space in the disk for storing more data.
➢ We may use invalid file name.
➢ We may attempt to perform an operation when the file is not
opened for that purpose.
65
Error handling functions

66
Random Access File
 Random file access enables us to read or write any data in our disk
file without having to read or write every piece of data before it.
 We can Quickly search for data, Modify data, delete data in a
random-access file.
 We can open and close Random access file same like Sequential files
with same opening mode, but we need a few new functions to
access files randomly, we find that the extra effort pays off in
flexibility, power, and speed of disk access.

67
68
Origin can be any of the three values, shown below:

 Example: seekg_beg.cpp
 Example: seekg_cur.cpp
 Example: seekg_end1.cpp

69

You might also like