Inheritance: Introduction, Protected Members and Class Access, Base Class Access
Specification, Constructors and Destructors in Base and Derived Classes, Class
Hierarchies, Polymorphism-Function Overloading, Function Overriding and Virtual
Member Functions, Abstract Base Classes and Pure Virtual Functions, Multiple
Inheritance.
UNIT-3
INHERIT
ANCE
▪ INTRODUCTION
▪ INHERITANCE is a key features of OOP in C++.
▪ It allows user to create new class from an existing class.
▪ The new class called as sub /derived/child class and existing
class called as super/base/parent class.
▪ Inheritance makes the code reusable.
▪ When we inherit an existing class, all its methods and fields
become available in the new class, hence code is reused.
▪ NOTE : all members of a class can inherited except PRIVATE
▪ Why INHERITANCE should be used?
▪ Suppose, in your game, you want three characters - a
maths teacher, a footballer and a businessman.
▪ Since, all of the characters are persons, they can walk and talk.
However, they also have some special skills. A maths teacher
can teach maths, a footballer can play football and a
businessman can run a business.
▪ You can individually create three classes who can walk, talk
and perform their special skill as shown in the figure below
▪ In each of the classes, you would be copying the same code
for walk and talk for each character.
▪ If you want to add a new feature - eat, you need to implement the same code
for each character. This can easily become error prone(like) (when copying)
and duplicate codes.
▪ It'd be a lot easier if we had a Person class with basic features like talk, walk,
eat, sleep, and add special skills to those features as per our characters. This
is done using inheritance.
▪ Using inheritance, now you don't implement the same code for walk and talk
for each class. You just need to inherit them.
▪ So, for Maths teacher (derived class), you inherit all features of a Person
(base class) and add a new feature TeachMaths. Likewise, for a footballer,
you inherit all the features of a Person and add a new
feature PlayFootball and so on.
▪ Implementation of Inheritance in C++ Programming
class Person
{ ... .
. ...
};
class MathsTeacher : public Person
{ ... ..
...
};
class Footballer : public Person
{ ....
.. ...
};
▪ In the beside example, class Person is a base class and
classes MathsTeacher and Footballer are the derived from Person.
▪ The derived class appears with the declaration of a class followed by a colon,
the keyword public and the name of base class from which it is derived.
▪ Since, MathsTeacher and Footballer are derived from Person, all data member
and member function of Person can be accessible from them.
Program for inheritance
#include <iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class Person
{
public:
char profession; //DM
int age;
Person()
{
Strcpy(Profession,"unemployed");
age=16;
}
void display()
{
cout << "My profession is: "<profession<<endl;
cout << "My age is: " << age << endl;
walk();//MF
talk(); //MF
}
void walk()
{
cout << "I can walk." << endl;
}
void talk()
{
cout << "I can talk." << endl;
}
};
int main()
{
MathsTeacher teacher;//teacher is obj
strcpy([Link] ,"Teacher“);
[Link] = 23;
[Link]();
[Link]();//defined in maths class
Footballer footballer;
strcpy([Link], "Footballer“);
[Link] = 19;
[Link]();
[Link]();
return 0;
Getch()
}
Output:
My profession is: Teacher
My age is: 23
I can walk.
I can talk.
I can teach Maths.
My profession is: Footballer
My age is: 19
I can walk.
I can talk.
I can play Football.
▪ PROTECTED MEMBERS AND CLASS ACCESS
▪ You can declare a derived class from a base class either different access
control/specifier. i.e., public inheritance, protected inheritance and private
inheritance.
▪ Access specifier defines the scope of members of base class into derived class.
▪ C++ supports the following access specifier:
1. Private specifier
2. Protected specifier
3. Public specifier
1. Private specifier : scope of private members are restricted to its own class.
Private members can’t be accessed by derived class or in main()function.
2. Protected specifier: scope of protected members are restricted to its own
class and derived class. Protected members can be accessed by derived
class but they can’t be accessed in main()function.
3. Public specifier :public members can be accessed by its own class,
derived class and in main()function.
class base
{
.... ... ....
};
class derived : access_specifier base
{
.... ... ....
};
Note: Either public, protected or private keyword is used in place
of access_specifier term used in the above code.
class base
{
public:
int x;
protected:
int y;
private:
int z;
};
class publicDerived: public base
{
// x is public
// y is protected
// z is not accessible from publicDerived
};
class protectedDerived: protected base
{
// x is protected
// y is protected
// z is not accessible from protectedDerived
};
class privateDerived: private base
{
// x is private
// y is private
// z is not accessible from privateDerived
}
Base has three member variables: x, y and z which
are public, protected and private member respectively.
publicDerived inherits variables x and y as public and protected. z is not
inherited as it is a private member variable of base.
protectedDerived inherits variables x and y. Both variables become
protected. z is not inherited If we derive a
class derivedFromProtectedDerived from protectedDerived, variables x and y
are also inherited to the derived class.
privateDerived inherits variables x and y. Both variables become private. z is
not inherited If we derive a class derivedFromPrivateDerived from
privateDerived, variables x and y are not inherited because they are private
variables of privateDerived.
class protectedDerived: protected base
{
// x is protected
// y is protected
// z is not accessible from protectedDerived
};
class privateDerived: private base
{
// x is private
// y is private
// z is not accessible from privateDerived
}
Base has three member variables: x, y and z which
are public, protected and private member respectively.
publicDerived inherits variables x and y as public and protected. z is not
inherited as it is a private member variable of base.
protectedDerived inherits variables x and y. Both variables become
protected. z is not inherited
If we derive a class derivedFromProtectedDerived from protectedDerived,
variables x and y are also inherited to the derived class.
privateDerived inherits variables x and y. Both variables become private. z is
not inherited
If we derive a class derivedFromPrivateDerived from privateDerived, variables
x and y are not inherited because they are private variables of privateDerived.
Accessibility in Public Inheritance
Accessibility private protected public
variables variables variables
Accessible from own class? yes yes Yes
Accessible from derived no yes Yes
class?
Accessible from 2nd derived no yes yes
class?
Accessibility in Protected Inheritance
Accessibility private protected public
variables variables variables
Accessible from own class? yes yes Yes
Accessible from derived no yes Yes(inherited
class? as a
protected
variable)
Accessible from 2nd derived no yes yes
class?
Accessibility in Private Inheritance
Accessibility private protected public variables
variables variables
Accessible from own yes yes yes
class?
Accessible from derived no Yes (inherited as a Yes (inherited as a
class? private variable) private variable)
variables)Accessible from no no no
2nd derived class?
▪ BASE CLASS ACCESS SPECIFICATION
Below is the access specification of class derived from base class:
▪ CLASS HIERARCHIES
C++ supports six types of inheritance as follows:
❑ SINGLE Inheritance
❑ MULTILEVEL Inheritance
❑ MULTIPLE Inheritance
❑ HIERARCHICAL Inheritance
❑ HYBRID Inheritance
❑ MULTIPATH Inheritance
1.SINGLE INHERITANCE
A derived class with only one base class is called single inheritance
2.MULTILEVEL INHERITANCE
A derived class with one base class and that base class is a derived class of another
is called multilevel inheritance
▪ Here, class B is derived from the base class A and the class C is derived from the
derived class B
Multilevel program
#include <iostream>
using namespace std;
#include<conio.h>
class A
{
public:
void display()
{
cout<<"Base class content.";
} };
class B : public A
{
};
class C : public B
{
};
Int main()
{
//creating object of derived class
C obj;
[Link]();
Getch();
return 0;
}
o/p : Base class content
3.MULTIPLE INHERITANCE
A derived class with multiple base class is called multiple inheritance.
For example: A class Bat is derived from base classes Mammal and Winged
Animal. It makes sense because bat is a mammal as well as a winged
animal.
Multiple program
#include <iostream>
using namespace std;
#include<conio.h>
class Mammal
{
public: Mammal()
{
cout << "Mammals can give direct birth." << endl;
} };
class WingedAnimal
{
public: WingedAnimal()
{
cout << "Winged animal can flap." << endl;
} };
class Bat: public Mammal, public WingedAnimal
{
};
int main()
{
Bat b1;
return 0;
Getch();
}
Output :
Mammals can give direct birth. Winged animal can flap.
4.HIERARCHICAL INHERITANCE
Multiple derived classes with same base class are called hierarchical
inheritance.
For example: Physics, Chemistry, Biology are derived from Science class.
Syntax:
class base_class
{
..... ...
}
class first_derived_class: public base_class
{
... .. ...
}
class second_derived_class: public base_class
{
... .. ...
}
class third_derived_class: public base_class
{
... .. ...
}
5.HYBRID INHERITANCE
Combination of multiple and hierarchical inheritance is called hybrid
inheritance.
6.MULTIPATH INHERITANCE
A derived class with two base classes and these two base classes have one
common base class is called multipath inheritance
Here class D is derived from class B and C.
Class B and C are child of class A.
From the above two points, we can say class D is indirectly derived from class
A.
C++ STREAMS
❑ C++ input/output (I/O) are based on streams, which are sequence of bytes
flowing in and out of the programs(just like water flowing through a pipe)
❑ Input stream – In input operation, data bytes flow from an input source(such
as keyboard file, network)into program.(cin)
❑ Output stream - In output operations, data bytes flow from an output
source(such as console, file, network)(cout)
❑ Streams acts as an intermediaries between the programs and the IO devices
STREAM CLASSES
ios is the base class. The iostream class is derived from istream
and ostream classes.
The ifstream and ofstream are derived from istream and ostream,
respectively.
These classes handles input and output with the disk files.
The fstream.h header file contains a declaration of ifstream,
ofstream and fstream classes.
The iostream.h file contains istream, ostream and iostream classes and
included in the program while doing disk I/O operations.
The filebuf class contains input and output operations with files.
The streambuf class does not organize streams for input and output
operations, only derived classes of streambuf performs I/O operations.
These derived classes arranges a space for keeping input data and for sending
output data.
C++ I/O streams can be broadly divided into 2 categories.
1. Standard I/O - here data flow from standard I/O devices(hardware
device) to main memory.
a. Standard input operation is when data flows from keyboard to
main memory.
b. Standard output operation is when data flows from main
memory to display screen.
2. File I/O – here data flow from file to main memory.
a. File input operation is when data flows from file to main memory.
b. File output operation is when data flows from main memory to file.
CONSOLE OR STANDARD I/O STREAM CLASSES
The standard I/O stream classes are
1. ios: The stream class represents the super class to maintain common
stream properties such as format flag, field, width, precision and locale.
2. Ostream: The stream class represents the standard output stream and
is used to write on standard output device i.e, display screen.
3. istream: The stream represents the standard input stream and is used
to read information from standard input device i.e, keyboard.
4. iostream: The stream represents the standard I/O stream generally,
and has the capabilities of both ostream and istream which means it
can write information to display screeen, and read information from
keyboard.
To perform standard I/O processing in C++, header files < iostream> must
be included in your C++ source file.
FILE I/O STREAM CLASSES
The file I/O stream classes are
ofstream: provides o/p operation on files
ifstream: provides i/p operation on files
fstream: supports for simultaneous i/p & o/p operation on file
write information to files, and read information from files.
To perform file processing in C++, header files <iostream> and
<fstream> must be included in your C++ source file.
Unformatted I/O operations
Unformatted I/O operations can be divided into two categories:
1. Unformatted standard I/O operation.
2. Unformatted file I/O operation.
Unformatted console or standard I/O operation.
When a C++ program that includes the iostream classes is being executed,
four objects are created and initialized, they include the following ;
1.Cout
2.Cin
3.Cerr
4.Clog
1. Cout
Cout : writing to a file.
Cout is an instance of ostream class.
The cout object is connected to the standard output device, which usually
is the display screen.
We use stream insertion operator, which is written as <<.
The insertion operator << may be used more than once in a single
statement as shown below and endl is used to add a new-line at the
end of the line.
Syntax:
Char str[]= “hello C++”;
Cout << “ value of str is :” << str<< endl;
Cout<< program
#include< iostream>
Using namespace std;
#include < conio.h>
Int main ()
{
Char str[]= “hello C++”;
Cout <<“ value of str is:” <<str<< endl;
Getch();
Return 0;
}
Output:
value of str is: hello C++.
2. Cin
Cin: reading from file
Cin is an instance of istream class.
The cin object is connected to the standard input device, which usually
is the keyboard.
We use stream extraction operator, which is written as >>.
Stream extraction operator to extract the value and store it in the given
variables.
Stream extraction operator>> may be used more than once in a single
statement.
Cin>> name >> age ;
Cin>> name
Cin >> age
Cin>> program
Program:
#include < iostream>
Using namespace std;
#include < conio.h>
Int main()
{
Char name [50];
Cout << enter your name:”;
Cin >> name;
Cout << “Your name is : “<< name<< endl;
Getch()
Return 0;
Output:
enter your name : abc
Your name is: abc
3.cerr
Cerr is an instance of ostream class.
The cerr object is connected to the standard error device, which is also a
display screen but the object cerr is un-buffered( means immediately written
to device).
The cerr is also used as the stream insertion operator, which is written as <<.
Cerr<< program
#include <iostream>
Using namespace std;
# include <conio.h>
Int main ()
{
Char str [] = “ unable to read...”;
Cerr << “ error message : “ << str<< endl;
getch()
Return 0;
}
Output:
error message: unable to read ...
4.Clog
Clog is an instance of ostream class.
The clog object is connected to the standard error device, which is also a
display screen but the object clog is buffered.
The clog is also used as the stream insertion operator, which is written as <<.
Clog << program
# include <iostream>
Using namespace std;
#include <conio.h>
Int main()
{
Char str [] = unable to read...”;
Clog << “error message:” <<str << endl;
Getch();
Return 0;
}
Output:
error message: unable to read...
We would not be able to see any difference in cout , cerr , and clog with these
small examples, but while writing and executing big programs then difference
becomes obvious.
Unformatted File I/O operation
Streams provide a uniform way of dealing with data coming from the keyword
or the hard disk and going out to the screen or hard disk.
To open and close files, we create if stream and ofstream objects
iostream objects maintain flags that report on the state of your input and
output.
1. eof() : The function eof() returns TRUE if the iostream object has encountered
EOF, end of file.
2. bad() : The function bad() Returns TRUE if we attempt an invalid operation.
3. Fail() : The function fail() returns TRUE anytime bad() is true or an operation
fails.
4. Good() : The function good() returns TRUE anytime all three of the other
functions are FALSE
Opening Files for input and output
A file must be opened before we can read from it or write to it.
Either the ofstream or fstream object may be used to open file for writing.
ifstream object is used to open a file for reading purpose only.
Syntax for open file:
Void open(const char*filename, ios :: openmode mode);
ios- mode flag , Open- read or write
The first argument specifies the name and location of the file to be opened
Second argument defines the mode in which the file should be opened.
The default mode for ofstream object is “ios::out” i.e.,the file is opened
writing.
ofstream fout(“[Link]”);
The default mode for ifstream object is “ios::in” i.e.,the file is opened for
reading
ifstream fin(“[Link]”);
Changing the Default Behaviour of stream on open
The default behaviour upon opening a file is to create the file if doesn’t exist
and to truncate(deletes all its content) the file if doesn’t exist. if we don’t
want this default behaviour, we can provide with second argument(mode)
The mode in which the file can be opened
1. ios::app – Appends to the end of existing file rather than truncating them
2. ios::ate – Places us at the end of the file, but we can write
data anywhere in the file.
3. ios::in - Open file for reading
4. ios::out – Open file for writing
5. ios::trunc – The default behaviour causes existing files to be truncated.
6. ios::nocreate – If the file does not exist, the open fails.
7. ios::noreplace – If the file does already exist, the open fails.
For example: if we want to open a file in write mode and want to truncate it
in case already exists following is syntax
Syntax:
ofstream outfile; [Link](“[Link]”, ios::out|ios::trunc);
Outfile-filename,trunc – delete content
Similary we can open a file for reading and writing
purpose: fstream afile;
[Link](“[Link]”, ios::out | ios::in);
ios – reading, Open – writing
Closing a File
Automatically closes all the opened files.
Release all the allocated memory
But it is always a good pratice that a programmer should close all the opened
files before program termination.
Syntax: this will be used for fstream,ifstream, ofstream
void close();
Program to read and write from/to a file
#include<iostream>
Using namespace std;
#include<conio.h>
#include<fstream>
int main()
{
int a,b,c; //declare variables
ifstream [Link] //create file i/p stream obj
[Link](“my [Link]”); //open i/p file
fin>>a>>b; //read 2 values from i/p file
C=a+b; //result will store in c
ofstream fout; //writing a file
[Link](“my output,dat”) //open o/p file
Fout<<c<<endl; //write the result to o/p file
[Link](); //close o/p file
Polymorphism and Virtual member function
Polymorphism means more than one function with same name, with different
working.
Polymorphism can be static or dynamic.
In static polymorphism memory will be allocated at compile-time and is
also know as early binding and complier- time polymorphism
In dynamic polymorphism memory will be allocated at runtime and also
known as late binding and run-time polymorphism.
Function overloading and operator overloading are examples of static
polymorphism
Virtual Function is an example of dynamic polymorphism
Function Overloading: Function overloading is an example of static
polymorphism. More than one function with same name, with different
signature in a class or in a same scope is called function overloading.
Operator overloading: another example of static polymorphism is operator
overloading. Operator overloading is a way of providing new implementation
of existing operator to work with user-defined datatype.
Virtual Function: virtual function is an example of dynamic polymorphism.
Virtual function is used in situation, when we need to invoke derived class
function using base class pointer. We must declare base class function as
virtual keyword preceding its normal declaration. If we don’t use virtual
keyword in base class, base class pointer will always execute function defined
in base class.