0% found this document useful (0 votes)
15 views39 pages

Unit III Inheritance & Stream Class 2021

The document provides an overview of inheritance in C++, explaining its definition, types, and advantages. It details various inheritance types such as single, multilevel, multiple, hierarchical, hybrid, and multipath inheritance, along with visibility modes and the concept of polymorphism. Additionally, it covers constructors, destructors, virtual functions, abstract classes, and multiple inheritance, including example code snippets to illustrate these concepts.

Uploaded by

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

Unit III Inheritance & Stream Class 2021

The document provides an overview of inheritance in C++, explaining its definition, types, and advantages. It details various inheritance types such as single, multilevel, multiple, hierarchical, hybrid, and multipath inheritance, along with visibility modes and the concept of polymorphism. Additionally, it covers constructors, destructors, virtual functions, abstract classes, and multiple inheritance, including example code snippets to illustrate these concepts.

Uploaded by

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

1

Unit III - Inheritance


1. The mechanism of deriving a new class from existing class is known

as Inheritance Or Derivation

2. Inheritance is the mechanism of reusing and existing classes without

modifying them.

3. The class whose members are inherited is called the base class

or super class or parent class.

4. The class that inherits members from base class is called the

derived class or sub or child class.

5. The derived class inherits all properties or some properties from the

base class.

6. The derived class will have inherited properties and also its own

properties.

7. Inheritance IS-A relationship between 2 or more classes

8. Inheritance reduces duplication of code because u need not write

same code again and again.

9. Common characteristics object are place in base class and reused in

derived class.

2
C++ supports six types of inheritance as follows:

 Single Inheritance

 Multilevel Inheritance

 Multiple Inheritance

 Hierarchical Inheritance

 Hybrid Inheritance

 Multipath Inheritance

base class or super class or


parent class.

derived class or sub or


Sing child class.

Name,age,address,contactno…….. rno college group course fees

A derived class Person


with only one
base class is
called single IS-A
inheritance.
student

3
A derived class
with one base Person
class and that
base class is a
derived class of
another is
student
called
multilevel
inheritance.

exam

A derived class person employee


with multiple
base class is
called multiple
inheritance.

student

person

Multiple
derived classes
with same base
class is called student employee
hierarchical
inheritance.

4
combining A person
more than
one type of
inheritance is
called
B C student exam
hybrid
inheritance.

D result

person

A derived class
with two base
classes and student exam
these two base
classes have
one common
base class is
called
result
multipath
inheritance.

5
Advantages:-

1. Reusability : facility to use public methods of base class without


rewriting the same.
2. Reduce code duplication.
3. Extensibility : extending the base class functionality within child
classes.

4. Data hiding : base class can decide to keep some data private so that
it cannot be altered by the derived class
5. Large Code is easy to manage and divided into parent and child
classes.

6
protected members and class access , base class speicification.
1. Protected members of a base class are like private members, which
are accessed by derived class.
2. The base class spcification determines how private , public, protected
members are accessed when they are inherited by the derived classes.

Modes of Inheritance
1. The private member is not inheritable.
2. So, C++ introduces a third visibility modifier, i.e., protected.
3. The member which is declared as protected will be accessible to all
derived classes.

Visibility modes can be classified into three categories:

1. Public: When the member is declared as public, it is accessible to all


the functions of the program.

2. Private: When the member is declared as private, it is accessible


within the class only.

3. Protected: When the member is declared as protected, it is accessible


within its own class as well as the class immediately derived from it.

7
Visibility of Inherited Members
Base class Derived class visibility
visibility

Public Private Protected

Private Not Not Not Inherited


Inherited Inherited

Protected Protected Private Protected

Public Public Private Protected

Defining base class:


Base class has fputures that are common to all the derived classes .
This allows Hierarchy Of Classes .
class baseclass
{
//Body of base class
};

Defining derived class:


A derived class can be defined by specifying its relationship with base
class in addition with its own features.

The colon operator : indicates that the derived class is derived from
base class
class baseclass
{
//Body of base class
};

8
class derivedclass : Visibilitymode baseclass
{
//Body of derived class
};

Visibility mode specifies whether the fputures of base class are


visible to derived class .

It may be private or public or protected but by default it is private

class a
{
protected:
member of class a;
};
class b : public a
{
member of class b;
};

9
//Program to show single inheritance
#include<iostream>
using namespace std;

class person
{ Person
protected:
char sname[10];
public:
void get1() student
{
cout<<"input sname"<<endl;
cin>>sname;
}
};
class student : public person
{
private:
char course[20];
public :
void get2()
{
cout<<"input course"<<endl;
cin>>course;
}
void put()
{
cout<<"sname: "<<sname<<endl;
cout<<"course: "<<course<<endl;
}

};

10
int main()
{
student s;
s.get1();
s.get2();
s.put();
return(0);
}

11
Class hierarchies(multilevel inheritance)
1. A base class can be derived from another base class.

2. In some situations, it is necessary to establish class hierarchies in


which A derived class with one base class and that base class is a derived
class of another is called multilevel inheritance.

3. Following example shows, class hierarchies of many layers.

//Program to show multilevel inheritance


#include<iostream>
using namespace std;

class person Person


{ sname
protected: get1()
char sname[10];
public:
void get1() Student
{ course
cout<<"input sname"<<endl; get2()
cin>>sname;
}
};
Exam

grade
get3() , put()

12
class student : public person
{
protected:
char course[20];
public :
void get2()
{
cout<<"input course"<<endl;
cin>>course;
}
};

class exam : public student


{
private:
int grade;
public :
void get3()
{
cout<<"input grade points"<<endl;
cin>>grade;
}
void put()
{
cout<<"sname is " << sname <<endl;
cout<<"course is " << course <<endl;
cout<<”grade points ” << grade;
}
};

13
int main()
{
exam e;
e.get1();
e.get2();
e.get3();

e.put();
return(0);
}

Output:

14
Constructors and destructors in inheritance

1. Constructors are special member functions to initialise objects of the


class. classname();

2. Destructors are special member functions to destroy objects of the


class. ~ classname();
3. When an object of the derived class is crputed , the compiler first
call the base class constructor and then the constructor of the derived
class.
4. Constructors are called from top to bottom of the class hierarchy .

5. This because the derived class is built up on the members of the


base class.

6. When the object of a derived class destroyed, first the derived class
destructor is invoked followed by the base class destructor.

7. Destructors are called in reverse order from bottom to top

15
#include<iostream>
using namespace std;

class A
{
public:
A() // default cons without arguments
{
cout<<"Constructor of A class..."<<endl;
}
~A()
{
cout<<"Destructor of A class.... "<<endl;
}
};

…………………………..continued next page

16
class B : public A
{
public :
B()
{
cout <<"Constructor of B ..."<<endl;
}
~B()
{
cout << "\nDestructor of B ..."<<endl;
}
};

class C : public B
{
public :
C()
{
cout << "Constructor of C ..."<<endl;
}
~C()
{
cout << "\nDestructor of C ...";
}
};

int main()
{
C x;
return (0);
}
Output:
Constructor of A class...
Constructor of B class...
Constructor of C class...

Destructor of C ..
Destructor of B ..
Destructor of A ...

17
Polymorphism
1. The term "Polymorphism" greek term .

2. The word "poly" means many and “morphism” means forms.

3. So polymorphism means many forms that is

one name having many forms

4. Polymorphism concept is

"single interface having multiple implementations."

5. The ability of function or operator or object existing in

more than one form.

6. Operator overloading

+ used for adding numbers and strings

10 + 20 addition operator

Hello + bye string operator

Function overloading

Sum(int a, int b);

Sum(float a, float b)

Note: Function Overloading concept refer UNIT I NOTES

18
Compile time polymorphism:

1. The overloaded functions are invoked by matching the type and


number of arguments.
2. This information is available at the compile time and, therefore,
compiler selects the appropriate function at the compile time,
which is also known as static binding or early binding.

19
If we define two or more functions having same name but different
type of arguments, it is known as overloading.

1. Function overloading which is the process of using the same


name for two or more functions.

Void sum(int a, int b)

Void sum(int a, int b, int c)

Void sum(int a, double b);

2. Operator overloading is the mechanism of giving special


meaning to the existing operators.

4+5 <-- integer addition

“hello” + “byehello” <-- string concatenation

Run time polymorphism:

1. Run time polymorphism is achieved when the object's method is


invoked at the run time instead of compile time.
2. It is achieved by method overriding which is also known as dynamic
binding or late binding.
3. It is achieved by virtual functions and pointers.

20
Function Overriding

1. If derived class defines same function as defined in its base


class, it is known as function overriding .
2. It is used to achieve runtime polymorphism.
3. It enables you to provide specific implementation of the
function which is already provided by its base class.

#include <iostream>
using namespace std; Class A
class A Put()
{
public: Class B
void put()
Put()
{
cout<<"from class A"; from class A
} from class B
};
class B : public A
{
public:
void put()
{
cout<<"from class B";
}
};
int main()
{
B x; // x is object
x.put();
return (0);
} Output: from class B

21
Virtual member functions
1. A C++ virtual function is a member function in the base class that you
redefine in a derived class.
It is declared using the virtual keyword.
2. It is used to tell the compiler to perform dynamic linkage or late
binding on the function.
3. When the function is made virtual, C++ determines which function is
to be invoked at the runtime based on the type of the object pointed
by the base class pointer.
#include <iostream>
using namespace std;
class A
{ Class A
public:
virtual Put()
virtual void put()
{
cout << "from class A"<<endl; Class B
}
}; Put()
class B : public A
{
public:
void put()
{
cout << "from class B"<<endl;
}
};

int main()
{
A * p; //pointer of base class
B b; //object of derived class
p = &b;
p->put();
p->put(); //Late Binding occurs
} Output:
Class A
Class B

22
Abstract base classes and Pure Virtual Function

Pure Virtual Function


1. When the function has no definition in the base class and

declared as = 0 , such function is known as "do-nothing"

function.

2. The "do-nothing" function is known as a Pure Virtual

Function. A pure virtual function is a function declared in

the base class that has no definition relative to the base

class.

class base
{
virtual void put()=0;
};

3. A pure virtual function should be redefined in derived class

compulsory.

4. A virtual function is not used for performing any task.

5. A class containing a pure virtual function which cannot be

used to create objects of its own, such classes are known as

Abstract Base Classes.

23
program to show pure virtual function and abstract class
#include <iostream>
using namespace std;
class A // abstract class
{
public:
virtual void put() =0; // pure virtual function
};

class B : public A
{ abstract base class
public: Class A
void put()
Virtual Put()=0
{
cout << "from class B";
Class B
}
}; Put()

int main()
{
A * p; //pointer of base class
B b; //object of derived class
p = &b;
p->put(); //Late Binding occurs

Output:

From class B

24
Abstract classes

1. Abstract classes are the way to achieve abstraction in C++.


2. Abstraction in C++ is the process to hide the internal details
and showing functionality only.
3. Abstraction can be achieved by two ways:

A. Abstract class
B. Interface

1. In C++ class is made abstract by declaring at least one of


the function as pure virtual function.
2. A pure virtual function is specified by placing "= 0" in its
declaration.
3. Its implementation must be provided by derived classes.

25
Multiple Inheritance

When a derived class has two or more base class is known as


Multiple Inheritance.

Person Employee

Teacher

Syntax: Example:
class A class person
{ {
}; };
class B class employee
{
{
};
}; class teacher : public person, public employee
class C : public A, public B {
{ };
};

26
Program to show multiple inheritance
#include<iostream.h>
using namespace std;
class person
{
protected:
person employee
char name[10];
public: name salary
void get1() get1() get2()
{
cout<<”input name:”<<endl;
cin>>name;
}
}; teacher

class employee subject


get3()
{ put()
protected:
double salary;
public:
void get2()
{
cout<<”input salary: ”<<endl;
cin>>salary;
}
};

Continued next page…………….

27
class teacher : pubic person , public employee
{
private:
char subject[10];
public:
void get3()
{
cout<<”input subject:”<<endl;
cin>>subject;
}
void put()
{
cout<< name<<salary<<subject;
}
};

int main()
{
teacher t;
t.get1();
t.get2();
t.get3();

t.put();
return(0);
}

28
Stream classes

1. A stream is a sequence of bytes flowing in and out of the


program.
2. The source stream that provides data to the program is
called the inputstream
3. The destination stream that recieves output from the
program is called output stream.
4. C++ has number of stream classes defined in iostream.h to
perform I/O operations with console devices and files.

Formatted I/o operations

29
ios class
This class is the base class for all stream classes.
The streams can be input or output streams.

istream Class

The istream class handles the input stream in the program .


The cin handles the input.
Syntax: example:
istream cin; char sname[10];
cin>>var; cin>>sname;

cin doesnot accept strings with spaces

ostream class

The ostream class handles the output stream in the program.


cout handle the output .

syntax: example:

ostream cout; char sname[10]=”anu”;


cout<<var; cout<<sname;

30
put() and get() functions:

1. The class istream and ostream have predefined


functions get() and put(), to handle single character input
and output operations.

2. get() reads a single character from the associated stream.


3. put() writes a single character to the associated stream.

Syntax:

char alpha;

cin.get(alpha);
cout.put(alpha)

31
porgram :
#include <iostream>
using namespace std;

int main()
{
char alpha;

cout<<”input character”<<endl;

cin.get(alpha);
cout.put(alpha);
return(0);
}

Output:
Input character A
A
=================================================

getline() and write() functions:

getline(): This function is used to input line of text .

Syntax:
cin.getline(variable, size);

example:
char sname[10];
cin.getline(sname,10);

getline accept strings with spaces.

32
write()
This function is used to output line of text .
Syntax:
cout.write(variable, size);

program to show getline() and write() functions.

#include <iostream>
using namespace std;

int main()
{
char sname[10];
cout<<"input sname";
cin.getline(sname,10);

cout.write(sname,5);
return(0);
}
Output:
input sname anu
anu

33
Formatted I/O in C++
C++ helps to format the I/O operations like

1. Alignment of field (text) to left , right .


2. Padding(filling) empty space with some character
3. Number of digits to be displayed after the decimal point
4. Converting from one number system to another base .

There are two ways to do so:


1. Using the ios class member functions.
2. Using manipulators(special functions)

ios class Member Functions Manipulators

1. width() setw()
2. precision() setprecision()
3. fill() setfill()
4. setf() setiosflags()
5. unsetf() resetiosflags()
endl
hex,dec,oct

34
ios class 5 member functions

1.width():
the width function is used to set the required field width.
cout.width(w);

eg:
cout.width(10);
cout<<”hello”;
cout.width(20);
cout<<”hai”;

output: hello hai

2.precision():
 It is used to set the number of digits printed to the right of the
decimal point.

cout.precision(number);
ex:
cout.precision(2);
cout<<45.5678;
output: 45.56

3.fill():
the fill method is used to set a character to fill in the blank space
of a field.
cout.fill(‘char’);
eg:
cout.width(10);
cout.fill(‘*’);
cout<<hello;
output: **********hello

35
4.setf():
setf() format flag that control the form of output display either
left justification or right justification.

cout.setf ( ios::left , ios::adjustified );


cout<<”hello”;
cout.setf( ios::right , ios::adjustified );
cout<<”hai”;

5.unsetf():
the unsetf method is used to remove the flag setting.

36
Manipulators
1. Manipulators are functions specifically designed to be used in
with the insertion (<<) and extraction (>>) operators on
stream objects.
2. In the program, include < iomanip.h> header file for using
these manipulators .
3. The following are manipulators:
A. endl
B. setw
C. setfill
D. setprecision
E. hex,dec, oct

1.endl

This manipulator has the same functionality as ‘\n’.

#include<iostream>
int main()
{
cout <<"Hello"<<endl;
cout <<"World!";
}

2.setprecision

 it is used with floating point numbers.


 It is used to set the number of digits printed to the right of the
decimal point.
 This may be used in two forms:

1. fixed : prints in fixed notation


2. scientific : prints in scientific notation

37
Example

#include<iostream>
#include<iomanip>
int main()
{
long double pi =3.141592653589793239;

cout <"default precision (6): "<< pi <<endl;


cout <<"setprecision(10): "<< setprecision(10)<< pi ;
}

Output

default precision (6): 3.14159


setprecision(10): 3.141592654

3.setw
This manipulator is used to set the required field width.

Example

#include<iostream>
#include<iomanip>

int main()
{
cout<<setw(10)<<”hello”<<setw(20)<<”world”<<endl;
}

Output

hello world

38
4.setfill

 This is used after setw manipulator.


 It is used for filling the empty spaces with specified character.

Example:

#include <iostream>
#include <iomanip>
int main()
{
cout<< setw(15) << setfill('*') <<”hello”;
return(0);
}
************hello

5.hex, dec, oct:

it converts decimal number to hexadecimal(base 16) ,


octal (base 8)
#include <iostream.h>
#include <iomanip.h>

int main()
{
int n=52; //decimal number
cout<< dec <<n <<endl;
cout<< hex <<n <<endl;
cout<< oct <<n;

return(0)
}

Output:

Decimal Number=52
Hexadecimal Number=34
Octal Number=64

39

You might also like