0% found this document useful (0 votes)
17 views16 pages

Unit - 4

Uploaded by

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

Unit - 4

Uploaded by

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

UNIT- IV INHERITANCE AND POLYMORPHISM

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.

Example syntax for creating a base class:

class Base {

public:

int a; // Example member variable


};
1.3 Derived Class: A class that is created from an existing class. The derived class inherits all
members and member functions of a base class. The derived class can have more functionality
with respect to the Base class and can easily access the Base class. A Derived class is also
called a child class or subclass.
• Derived Classes: A Derived class is defined as the class derived from the base class.
Syntax:
class <derived_class_name> : <access-specifier> <base_class_name>
{
//body
}
Where
class — keyword to create a new class
derived_class_name — name of the new class, which will inherit the base class
access-specifier — either of private, public or protected. If neither is specified,
PRIVATE is taken as default
base-class-name — name of the base class
• Note: A derived class doesn’t inherit access to private data members. However, it does
inherit a full parent object, which contains any private members which that class
declares.
1.4 Visibility modes
When a base class is derived by a derived class with the help of inheritance, the
accessibility of base class by the derived class is controlled by visibility modes.
Types of Visibility modes:

There are three types of Visibility modes:


1. Public Visibility mode: If we derive a subclass from a public base
class. Then the public member of the base class will become public
in the derived class and protected members of the base class will
become protected in the derived class.
2. Protected Visibility mode: If we derive a subclass from a Protected base
class. Then both public member and protected members of the base class
will become protected in the derived class.
3. Private Visibility mode: If we derive a subclass from a Private base class.
Then both public member and protected members of the base class will
become Private in the derived class.
Types of Inheritance
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
1.5 Single Inheritance: In single inheritance, a class is allowed to inherit from only one
class. i.e. one subclass is inherited by one base class only.

Syntax:
class subclass_name : access_mode base_class
{
// body of subclass
};
OR
class A
{
... .. ...
};
class B: public A
{
... .. ...
};

// C++ program to explain Single inheritance


#include<iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};

// sub class derived from a single base classes


class Car : public Vehicle {

};

// 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 subclass_name : access_mode base_class1, access_mode base_class2, ....


{
// body of subclass
};

class B
{
... .. ...
};

class C
{
... .. ...
};

class A: public B, public C


{
... ... ...
};

// C++ program to explain Multiple inheritance


#include <iostream>
using namespace std;

// first base class


class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// second base class


class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle\n";
}
};

// sub class derived from two base classes


class Car : public Vehicle, public FourWheeler {
};

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

using namespace std;

/* start of Enclosing class declaration */


class Enclosing {
private:
int x;

/* start of Nested class declaration */


class Nested {
int y;
void NestedFun(Enclosing *e) {
cout<<e->x; // works fine: nested class can access
// private members of Enclosing class
}
}; // declaration Nested class ends here
}; // declaration Enclosing class ends here

int main()
{

Program 2
#include<iostream>

using namespace std;

/* start of Enclosing class declaration */


class Enclosing {

int x;

/* start of Nested class declaration */


class Nested {
int y;
}; // declaration Nested class ends here

void EnclosingFun(Nested *n) {


cout<<n->y; // Compiler Error: y is private in Nested
}
}; // declaration Enclosing class ends here

int main()
{

1.9 Polymorphism

 The word “polymorphism” means having many forms.


 In simple words, we can define polymorphism as the ability of a message to be
displayed in more than one form.
 A real-life example of polymorphism is a person who at the same time can have
different characteristics.
 A man at the same time is a father, a husband, and an employee. So the same person
exhibits different behavior in different situations. This is called polymorphism.
 Polymorphism is considered one of the important features of Object-Oriented
Programming.

Types of Polymorphism

1. Compile-time Polymorphism
2. Runtime Polymorphism

1. Compile-time Polymorphism

 This type of polymorphism is achieved by function overloading or


operator overloading.

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.

// C++ program to demonstrate function overloading or Compile-time Polymorphism


#include <bits/stdc++.h>
using namespace std;
class Geeks {
public:
// Function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}
// Function with same name but 1 double parameter
void func(double x)
{
cout << "value of x is " << x << endl;
}

// Function with same name and


// 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y
<< endl;
}
};

// Driver code
int main()
{
Geeks obj1;

// Function being called depends


// on the parameters passed
// func() is called with int value
obj1.func(7);

// func() is called with double value


obj1.func(9.132);

// func() is called with 2 int values


obj1.func(85, 64);
return 0;
}
Output
value of x is 7
value of x is 9.132
value of x and y is 85, 64

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.

// C++ program to demonstrate Operator Overloading or Compile-Time Polymorphism


#include <iostream>
using namespace std;

class Complex {
private:
int real, imag;

public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}

// This is automatically called


// when '+' is used with between
// two Complex objects
Complex operator+(Complex const& obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

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

// C++ program for function overriding with data members


#include <bits/stdc++.h>
using namespace std;

// base class declaration.


class Animal {
public:
string color = "Black";
};

// inheriting Animal class.


class Dog : public Animal {
public:
string color = "Grey";
};

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

Some Key Points About Virtual Functions:

 Virtual functions are Dynamic in nature.


 They are defined by inserting the keyword “virtual” inside a base class
and are always declared with a base class and overridden in a child
class
 A virtual function is called during Runtime

Below is the C++ program to demonstrate virtual function:

// C++ Program to demonstrate the Virtual Function


#include <iostream>
using namespace std;

// Declaring a Base class


class GFG_Base {

public:
// virtual function
virtual void display()
{
cout << "Called virtual Base Class function"
<< "\n\n";
}

void print()
{
cout << "Called GFG_Base print function"
<< "\n\n";
}
};

// Declaring a Child Class


class GFG_Child : public GFG_Base {

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;

// This will call the virtual function


base->GFG_Base::display();

// this will call the non-virtual function


base->print();
}
Output
Called virtual Base Class function
Called GFG_Base print function

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.

File open for writing: the internal stream buffer supports


out output
output 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.

All output operations happen at the end of the file, appending


app append
to its existing contents.

Any contents that existed in the file before it is open are


trunc truncate
discarded.

Default Open Modes:

ifstream ios::in

ofstrea
ios::out
m

fstream ios::in | ios::out

You might also like