Unit - 4
Unit - 4
Syllabus
Inheritance – Base class – Derived Class – Visibility modes – Single Inheritance – Multilevel Inheritance
– Multiple Inheritance – Nesting – Polymorphism – File – Opening and Closing – File Modes – File
Pointers – Random Access – Error Handling
1.1 Inheritance
• The capability of a class to derive properties and characteristics from another class is
called Inheritance.
• Inheritance is one of the most important features of Object-Oriented Programming.
• Inheritance is a feature or a process in which, new classes are created from the existing
classes.
• The new class created is called “derived class” or “child class” and the existing class is
known as the “base class” or “parent class”.
• The derived class now is said to be inherited from the base class.
• It means, the derived class inherits all the properties of the base class, without changing
the properties of base class and may add new features to its own.
• These new features in the derived class will not affect the base class. The derived class
is the specialized class for the base class.
• Sub Class: The class that inherits properties from another class is called
Subclass or Derived Class.
• Super Class: The class whose properties are inherited by a subclass is called
Base Class or Superclass.
• Implementing inheritance in C++: For creating a sub-class that is inherited from the
base class we have to follow the below syntax.
1.2 Base Class: A base class is a class in Object-Oriented Programming language, from
which other classes are derived. The class which inherits the base class has all members of
a base class as well as can also have some additional properties. The Base class members
and member functions are inherited to Object of the derived class. A base class is also
called parent class or superclass.
class Base {
public:
Syntax:
class subclass_name : access_mode base_class
{
// body of subclass
};
OR
class A
{
... .. ...
};
class B: public A
{
... .. ...
};
// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
};
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Output
This is a Vehicle
1.6 Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit
from more than one class. i.e one subclass is inherited from more than one base class.
Syntax:
class B
{
... .. ...
};
class C
{
... .. ...
};
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}
Output
This is a Vehicle
This is a 4 wheeler Vehicle
1.7 Multilevel Inheritance: In this type of inheritance, a derived class is created from
another derived class.
Syntax: -
class C
{
... .. ...
};
class B:public C
{
... .. ...
};
class A: public B
{
... ... ...
};
// C++ program to implement Multilevel Inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
// first sub_class derived from class vehicle
class fourWheeler : public Vehicle {
public:
fourWheeler()
{
cout << "Objects with 4 wheels are vehicles\n";
}
};
// sub class derived from the derived base class fourWheeler
class Car : public fourWheeler {
public:
Car() { cout << "Car has 4 Wheels\n"; }
};
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}
Output
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels
1.8 Nesting
A nested class is a class which is declared in another enclosing class. A nested class is a
member and as such has the same access rights as any other member. The members of an
enclosing class have no special access to members of a nested class; the usual access rules
shall be obeyed.
For example, program 1 compiles without any error and program 2 fails in compilation.
Program 1
#include<iostream>
int main()
{
Program 2
#include<iostream>
int x;
int main()
{
1.9 Polymorphism
Types of Polymorphism
1. Compile-time Polymorphism
2. Runtime Polymorphism
1. Compile-time Polymorphism
a) Function Overloading
When there are multiple functions with the same name but different
parameters, then the functions are said to be overloaded, hence this is
known as Function Overloading.
Functions can be overloaded by changing the number of
arguments or/and changing the type of arguments.
In simple terms, it is a feature of object-oriented programming providing
many functions that have the same name but distinct parameters when
numerous tasks are listed under one function name.
There are certain Rules of Function Overloading that should be followed
while overloading a function.
// Driver code
int main()
{
Geeks obj1;
Explanation: In the above example, a single function named function func() acts differently in
three different situations, which is a property of polymorphism.
b) Operator Overloading
C++ has the ability to provide the operators with a special meaning for a
data type, this ability is known as operator overloading.
For example, we can make use of the addition operator (+) for string class
to concatenate two strings.
We know that the task of this operator is to add two operands.
So a single operator ‘+’, when placed between integer operands, adds
them and when placed between string operands, concatenates them.
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}
// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);
// An example call to "operator+"
Complex c3 = c1 + c2;
c3.print();
}
Output
12 + i9
Explanation: In the above example, the operator ‘+’ is overloaded. Usually, this operator is
used to add two numbers (integers or floating point numbers), but here the operator is made to
perform the addition of two imaginary or complex numbers.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding.
Late binding and dynamic polymorphism are other names for runtime
polymorphism.
The function call is resolved at runtime in runtime polymorphism.
In contrast, with compile time polymorphism, the compiler determines which
function call to bind to the object after deducing it at runtime.
a) Function Overriding
Function Overriding occurs when a derived class has a definition for one of
the member functions of the base class. That base function is said to be
overridden.
Runtime Polymorphism with Data Members
Runtime Polymorphism cannot be achieved by data members in C++. Let’s
see an example where we are accessing the field by reference variable of
parent class which refers to the instance of the derived class.
// Driver code
int main(void)
{
Animal d = Dog(); // accessing the field by reference
// variable which refers to derived
cout << d.color;
}
Output
Black
We can see that the parent class reference will always refer to the data member of the parent
class.
b) Virtual Function
A virtual function is a member function that is declared in the base class
using the keyword virtual and is re-defined (Overridden) in the derived
class.
public:
// virtual function
virtual void display()
{
cout << "Called virtual Base Class function"
<< "\n\n";
}
void print()
{
cout << "Called GFG_Base print function"
<< "\n\n";
}
};
public:
void display()
{
cout << "Called GFG_Child Display Function"
<< "\n\n";
}
void print()
{
cout << "Called GFG_Child print Function"
<< "\n\n";
}
};
// Driver code
int main()
{
// Create a reference of class GFG_Base
GFG_Base* base;
GFG_Child child;
base = &child;
1.10 File
File handling is used to store data permanently in a computer. Using file handling we can store
our data in secondary memory (Hard disk).
How to achieve the File Handling
For achieving file handling we need to follow the following steps:-
STEP 1-Naming a file
STEP 2-Opening a file
STEP 3-Writing data into the file
STEP 4-Reading data from the file
STEP 5-Closing a file.
Streams in C++:-
We give input to the executing program and the execution program gives back the output. The
sequence of bytes given as input to the executing program and the sequence of bytes that
comes as output from the executing program are called stream. In other words, streams are
nothing but the flow of data in a sequence.
The input and output operation between the executing program and the devices like keyboard
and monitor are known as “console I/O operation”. The input and output operation between the
executing program and files are known as “disk I/O operation”.
Classes for File stream operations: -
The I/O system of C++ contains a set of classes which define the file handling methods. These
include ifstream, ofstream and fstream classes. These classes are derived from fstream and
from the corresponding iostream class. These classes, designed to manage the disk files, are
declared in fstream and therefore we must include this file in any program that uses files.
1. ios:-
ios stands for input output stream.
This class is the base class for other classes in this class hierarchy.
This class contains the necessary facilities that are used by all the other derived classes for
input and output operations.
2. istream:-
istream stands for input stream.
This class is derived from the class ‘ios’.
This class handle input stream.
The extraction operator(>>) is overloaded in this class to handle input streams from files to
the program execution.
This class declares input functions such as get(), getline() and read().
3. ostream:-
ostream stands for output stream.
This class is derived from the class ‘ios’.
This class handle output stream.
The insertion operator(<<) is overloaded in this class to handle output streams to files from
the program execution.
This class declares output functions such as put() and write().
4. streambuf:-
This class contains a pointer which points to the buffer which is used to manage the input
and output streams.
5. fstreambase:-
This class provides operations common to the file streams. Serves as a base for fstream,
ifstream and ofstream class.
This class contains open() and close() function.
6. ifstream:-
This class provides input operations.
It contains open() function with default input mode.
Inherits the functions get(), getline(), read(), seekg() and tellg() functions from the istream.
7. ofstream:-
This class provides output operations.
It contains open() function with default output mode.
Inherits the functions put(), write(), seekp() and tellp() functions from the ostream.
8. fstream:-
This class provides support for simultaneous input and output operations.
Inherits all the functions from istream and ostream classes through iostream.
9. filebuf:-
Its purpose is to set the file buffers to read and write.
We can also use file buffer member function to determine the length of the file.
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in
fstream headerfile.
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
Now the first step to open the particular file for read or write operation. We can open file by
1. passing file name in constructor at the time of object creation
2. using the open method
For e.g.
Open File by using constructor
ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
ifstream fin(filename, openmode) by default openmode = ios::in
ifstream fin(“filename”);
Open File by using open method
Calling of default constructor
ifstream fin;
fin.open(filename, openmode)
fin.open(“filename”);
Modes :
Member Stands
Constant For Access
File open for reading: the internal stream buffer supports input
in * input
operations.
binary binary Operations are performed in binary mode rather than text.
ate at end The output position starts at the end of the file.
ifstream ios::in
ofstrea
ios::out
m