0% found this document useful (0 votes)
2 views7 pages

Unit III

The document discusses various inheritance types in C++, including single, multilevel, multiple, and hierarchical inheritance. It explains how classes can inherit properties and methods from base classes, emphasizing the importance of access specifiers (public, private, protected) in determining member visibility. The document also provides code examples to illustrate these concepts.

Uploaded by

shashankgujrati1
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)
2 views7 pages

Unit III

The document discusses various inheritance types in C++, including single, multilevel, multiple, and hierarchical inheritance. It explains how classes can inherit properties and methods from base classes, emphasizing the importance of access specifiers (public, private, protected) in determining member visibility. The document also provides code examples to illustrate these concepts.

Uploaded by

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

UNIT III int age;

char name [10];


public:
Inheritance: void get ( );
};
Reaccessability is yet another feature of OOP's. C++ strongly supports the concept of reusability. void worker : : get ( )
The C++ classes can be used again in several ways. Once a class has been written and tested, it can {
be adopted by another programmers. This is basically created by defining the new classes, reusing cout <<”yout name please”
the properties of existing ones. The mechanism of deriving a new class from an old one is called cin >> name;
'INHERTTENCE'. This is often referred to as IS-A' relationship because very object of the class cout <<”your age please” ;
being defined "is" also an object of inherited class. The old class is called 'BASE' class and thenew cin >> age;
one iscalled'DERIEVED'class. }
void worker :: show ( )
Defining DerivedClasses {
cout <<”In My name is :”<<name<<”In My age is :”<<age;
A derived class is specified by defining its relationship with the base class in addition to its own }
details. The general syntax of defining a derived class is as follows: class manager ::publicworker //derived class(publicly)
{
class d_classname : Access specifier baseclass name int now;
{ public:
void get ( ) ;
// members of derivedclass void show ( ) ;
}; };
The colon indicates that the a-class name is derived from the base class name. The access specifier or void manager : : get ( )
the visibility mode is optional and, if present, may be public, private or protected. By default it is {
private. Visibility mode describes the status of derived features e.g. worker : : get (); //the calling of base class input fn.
cout << “number of workers underyou”;
class xyz //baseclass cin >> now;
{ cin>>name>>age;
members of xyz } ( if they were public )
}; void manager :: show ()
class ABC :publicxyz //publicderivation {
{ worker :: show(); //calling of base class o/pfn.
members of ABC cout <<“in No. of workers under me are: “ << now;
}; }
class ABC: XYZ //private derivation (bydefault) main ( )
{ {
members of ABC clrscr ( ) ;
}; worker W1;
manager M1;
In the inheritance, some of the base class data elements and member functions are inherited into the M1 .get ( );
derived class. We can add our own data and member functions and thus extend the functionality of M1.show ( ) ;
the base class. Inheritance, when used to modify and extend the capabilities of the existing classes, }
becomes a very powerful tool for incremental program development. If you input the following to this program:

Single Inheritance Your name please

When a class inherits from a single base class, it is known as single inheritance. Following program Ravinder
shows the single inheritance using public derivation. Your age please

#include<iostream.h> 27
#include<conio.h> number of workers under you
class worker
{ 30

clrscr ( ) ;
worker wl ;
manager ml;
Then the output will be as follows:
ml.get ( ) ;
My name is : Ravinder ml.show ( );
}
My age is : 27
The following program shows the single inheritance using protected derivation
No. of workers under me are : 30
#include<conio.h>
The following program shows the single inheritance by private derivation. #include<iostream.h>
classworker //Base class declaration
#include<iostream.h>
{ protected:
#include<conio.h> int age; char name [20];
public:
classworker //Base classdeclaration
void get ( );
{ void show ( );
int age; };
char name [10] ; void worker :: get ()
public: {
void get ( ) ; cout >> “your name please”;
void show ( ) ; cin >>name;
}; cout << “your age please”;
void worker : : get ( ) cin >> age;
{ }
cout << “your name please” ; void worker :: show ( )
cin >> name; {
cout << “your age please”; cout << “in my name is: “ << name << “in my age is “ <<age;
cin >>age; }
} class manager:: protected worker // protected inheritance
void worker : show ( ) {
{ int now;
cout << “in my name is: “ <<name<< “in” << “my age is : “ <<age; public:
} void get ();
class manager : worker //Derived class (privately by default) void show ( ) ;
{ };
int now; void manager : : get ( )
public: {
void get ( ) ; cout << “please enter the name In”;
void show ( ) ; cin >> name;
}; cout<< “please enter the age In”; //Directly inputting thedata
void manager : : get ( ) cin>>age; members of baseclass
{ cout << “ please enter the no. of workers under you:”;
worker : : get ( ); //calling the get function of base cin >> now;
cout << “number of worker under you”; class which is }
cin >> now; void manager : : show ( )
}
void manager : : show ( ) {
{ cout « "your name is : "«name«" and age is : "«age;
worker : : show ( ) ; cout «"In no. of workers under your are : "«now;
cout << “in no. of worker under me are : “ <<now; main ( )
} {
main ( ) clrscr ( ) ;
{ manager ml;
ml.get ( ) ;
cout « "\n \n";
ml.show ( );
} Multilevel Inheritance
When the inheritance is such that, the class A serves as a base class for a derived class B which in
Making a Private Member Inheritable turn serves as a base class for the derived class C. This type of inheritance is called „MULTILEVEL
INHERITENCE‟. The class B is known as the „INTERMEDIATE BASE CLASS‟ since it provides a
Basically we have visibility modes to specify that in which mode you are deriving the another class link for the inheritance between A and C. The chain ABC is called „ITNHERITENCE*PATH‟ for
from the already existing base class. They are: e.g.

a. Private: when a base class is privately inherited by a derived class, 'public


members' of the base class become private members of the derived class and
A Base class
therefore the public members of the base class can be accessed by its own
objects using the dot operator. The result is that we have no member of base class
that is accessible to the objects of the derivedclass.
b. Public: On the other hand, when the base class is publicly inherited, 'public
members' of the base class become 'public members' of derived class and
therefore they are accessible to the objects of the derivedclass. Inheritance path B Intermediate base
c. Protected: C++ provides a third visibility modifier, protected, which serve a class
little purpose in the inheritance. A member declared as protected is accessible
by the member functions within its class and any class immediately derived
from it. It cannot be accessed by functions outside these twoclasses.
C
Derived class
The below mentioned table summarizes how the visibility of members undergo modifications when
they are inherited
The declaration for the same would be:
Derived Class Visibility Class A
Base Class Visibility
Public Private Protected {
Private X X X //body
Public Public Private Protected }
Class B : public A
Protected Protected Private Protected
{
//body
}
The private and protected members of a class can be accessed by: Class C : public B
{
a. A function i.e. friend of aclass. //body
b. A member function of a class that is the friend of theclass. }

c. A member function of a derived class. This declaration will form the different levels of inheritance.

Following program exhibits the multilevel inheritance.

#include<iostream.h>
#include<conio.h>
classworker // Base classdeclaration
{
int age;
char name [20] ;
public;
void get( ) ;

void show( ) ;
}

main ( )
{
void worker: get ( ) clrscr ( ) ;
{ ceo cl ;
cout << “your name please” ; cl.get ( ) ; cout << “\n\n”;
cin >> name; cl.show ( ) ;
cout << “your age please” ; }
} Worker
void worker : : show ( )
{ Private:
cout << “In my name is : “ <<name<< “ In my age is : “ <<age; int age;
} char name[20];
class manager : public worker //Intermediate base class derived
{ //publicly from the base class Protected:
intnow;
public: Private:
void get ( ) ; int age;
void show( ) ; char name[20];
};
void manager :: get ( ) Manager:Worker
{
worker : :get (); //calling get ( ) fn. of base class Private:
cout << “no. of workers under you:”; int now;
cin >> now;
} Protected:
void manager : : show ( )
{ Public:
worker : : show (); //calling show ( ) fn. of base class void get()
cout << “In no. of workers under me are: “<<now; void show()
} worker::get()
class ceo:publicmanager //declaration of derivedclass worker::get()
{ //publicly inherited fromthe
intnom; //intermediate baseclass
public: Ceo: Manager
void get ( ) ;
void show ( ) ; Public:
};
void ceo : : get ( ) Protected:
{
manager : : get ( ) ; Public:
cout << “no. of managers under you are:”; cin >> nom; All the inherited
} members

void manager : : show ( )


{
cout << “In the no. of managers under me are: In”;
cout << “nom;
}
Multiple Inheritances
A class can inherit the attributes of two or more classes. This mechanism is known as „MULTIPLE
public:
INHERITENCE‟. Multiple inheritance allows us to combine the features void get ( )
{
of several existing classes as a starring point for defining new classes. It is like the child inheriting cout << “mother‟s name please” << “In”;
the physical feature of one parent and the intelligence of another. The syntax of the derived class is cin >> name;
asfollows: cout << “mother‟s age please” << “in”;
cin >> age;
Class base1 Class base2 }
{ { void show ( )
//body1 // body2 {
} } cout << “In my mother‟s name is: “ <<name;
cout << “In my mother‟s age is: “ <<age;
}
class daughter : public father, public mother //derived class inheriting
{ //publicly
char name[20]; //the features of both the baseclass
Class derived : visibility basel, visibility base2
intstd;
{
public:
//body3
void get ( ) ;
}
void show ( ) ;
};
Where the visibility refers to the access specifiers i.e. public, private or protected. Following void daughter :: get ( )
program shows the multipleinheritance. {
father :: get ( ) ;
#include<iostream.h> mother :: get ( ) ;
cout << “child's name: “;
#include<conio . h>
cin >> name;
classfather //Declaration of baseclassl
cout << “child's standard”;
{
int age ; cin >> std;
char flame [20] ; }
public: void daughter :: show ()
{
void get ( ) ;
void show ( ) ; father :: show ();
nfather :: show ( ) ;
};
void father : : get ( ) cout << “In child‟s name is : “ <<name;
cout << “In child's standard: “ << std;
{
cout << “your father name please”; }
cin >> name; main ( )
cout << “Enter the age”; {
cin >> age; clrscr ( ) ;
daughter d1;
}
d1.get ( ) ;
void father : : show ( )
d1.show ( ) ;
{
cout<< “In my father‟s name is: „ <<name<< “In my father‟s age is:<<age; }
}
classmother //Declaration of base class 2
{
char name [20] ;
int age ;

Hierarchical Inheritance
Diagrammatic Representation of Multiple Inheritance is asfollows: Another interesting application of inheritance is to use is as a support to a hierarchical design of a
class program. Many programming problems can be cast into a hierarchy where certain features of
Father Mother one level are shared by many others below that level for e.g.

Private: Private: Accounts


int age; int age;
char name[20]; char name[20]; Saving Accounts Current Accounts

Protected: Protected:

Public: Public:
void get() void get()
Fixed deposit
void show() void show()
Short term Long term
Mid term

In general the syntax is given as


Class daughter: public Father, publicMother
Class A
{
Private: char name[20]; int age; // body A
}
Protected:

Public: Class C: public A


//self Class B: public A {
void get(); void showQ; { //body B
//from Father //body B }
void get(); void show(); }
//from Mother
void get(); void show();
In C++, such problems can be easily converted into hierarchies. The base class will include all the
features that are common to the subclasses. A sub-class can be constructed by inheriting the features
of base class and so on.

// Program to show the hierarchical inheritance


#include<iostream.h>
# include<conio. h>
classfather //Base classdeclaration
{
int age;
char name [15];
public:
void get ( )
{
cout<< “father name please”; cin >> name;
cout<< “father‟s age please”; cin >> age; son S1;
} daughter D1 ;
void show ( ) S1. get ( );
{ D1. get ( ) ;
cout << “In father‟s name is „: “<<name; S1 .show( ) ;
cout << “In father‟s age is: “<< age; D1. show ( ) ;
} }
};
Hybrid Inheritance
class son :publicfather //derived class1
{ There could be situations where we need to apply two or more types of inheritance to design a
char name [20] ; program. Basically Hybrid Inheritance is the combination of one or more types of the inheritance.
int age ; Here is one implementation of hybrid inheritance.
public;
void get ( ) ;
void show ( ) ; //Program to show the simple hybridinheritance
}; #include<i sos t ream. h>
void son : : get ( ) #include<conio .h>
classstudent //base classdeclaration
{
protected:
int r_no;
{ public:
father :: get ( ) ; void get _n (int a)
cout << “your (son) name please” << “in”; cin >>name; {
cout << “your age please” << “ln”; cin>>age; r_no =a;
} }
void son :: show ( ) void put_n (void)
{ {
father : : show ( ) ; cout << “Roll No. : “<< r_no;
cout << “In my name is : “ <<name; cout << “In”;
cout << “In my age is : “ <<age; }
} };
class daughter :publicfather //derived class2. class test : public student
{ { //Intermediate baseclass
char name [15] ; protected : int parti, par2;
int age;
public: public :
void get ( ) void get_m (int x, int y) {
{ parti = x; part 2 = y; }
father : : get ( ) ; void put_m (void) {
cout << “your (daughter‟s) name please In” cin>>name; cout << “marks obtained: “ << “In”
cout << “your age please In”; cin >>age; << “Part 1 = “ << part1 << “in”
} << “Part 2 = “ << part2 << “In”;
void show ( ) }
{ };
father : : show ( ) ; classsports // base forresult
cout << “in my father name is: “ << name << “ {
In and his age is : “<<age; protected : int score;
} public:
}; void get_s (int s){
main ( ) score = s }
{ void put_s (void){
clrscr ( ) ; cout << “ sports wt. : “ << score << “\n\n”;

}
};
Virtual Base Classes
class result : public test, public sports //Derived from test
&sports We have just discussed a situation which would require the use of both multiple and multi level
{ inheritance. Consider a situation, where all the three kinds of inheritance, namely multi-level,
int total; multiple and hierarchical are involved.
public:
void display (void); Let us say the 'child' has two direct base classes „parent1‟ and „parent2‟ which themselves has a
}; common base class „grandparent‟. The child inherits the traits of „grandparent‟ via two separate
paths. It can also be inherit directly as shown by the broken line. The grandparent is sometimes
referred to as „INDIRECT BASE CLASS‟. Now, the inheritance by the child might cause some
void result : : display (void) problems. All the public and protected members of „grandparent‟ are inherited into „child‟ twice, first
{ via „parent1‟ and again via „parent2‟. So, there occurs a duplicacy which should beavoided.
total = part1 + part2 + score;
put_n ( ) ;. The duplication of the inherited members can be avoided by making common base class as the
put_m ( ); virtual base class: fore.g.
put_S ( ); classg_parent
cout << “Total score: “ <<total<< “\n” {
} //Body
main ( ) };
{ class parent1: virtual public g_parent
clrscr ( ) ; {
result S1; // Body
S1.get_n (347) ; };
S1.get_m (30, 35);
S1.get_s (7) ; class parent2: public virtual g_parent
S1.dciplay ( ) ; {
}
// Body
};
class child : public parent1, public parent2
{
// body
};

When a class is virtual base class, C++ takes necessary care to see that only one copy
of that class is inherited, regardless of how many inheritance paths exists between
virtual base class and derived class. Note that keywords „virtual‟ and „public‟ can be
used in eitherorder.

//Program to show the virtual base class


#include<iostream.h>
#include<conio . h>
classstudent // Base classdeclaration
{
protected:
int r_no;
public:
void get_n (inta)
{ r_no = a; }
void put_n(void)
{ cout << “Roll No. “ << r_no<< “ln”;}
};
class test : virtual public student // Virtually declaredcommon protected:
{ //base class 1 int x;
protected: public:
int part1; void get (int) ;
int part2; void show (void) ;
public: };
void get_m (int x, int y) void A : : get (int a)
{ part1= x; part2=y;} {x=a;}
void putm (void) void A : : show(void)
{ { cout << X ;}
cout << “marks obtained: “ << “\n”; Class A1 : Virtual PublicA
cout << “part1 = “ << part1 << “\n”; {
cout << “part2 = “<< part2 << “\n”;
}
};
class sports : public virtual student // virtually declared common
{ //base class 2
protected:
int score; protected:
public: int y ;
void get_s (int a) { public:
score = a ; void get (int) ;
} void show (void);
void put_s (void) };
{ cout << “sports wt.: “ <<score<< “\n”;} void A1 :: get (int a)
}; { y = a;}
class result: public test,publicsports //derivedclass void A1 :: show (void)
{ {
private : int total ; cout <<y ;
public: {
void show (void) ; class A2 : Virtual public A
}; {
void result : : show (void) protected:
{ total = part1 + part2 + score ; int z ;
put_n ( ); public:
put_m ( ); void get (int a)
put_s ( ) ; cout << “\n total score= “ <<total<< “\n” ; { z =a;}
} void show (void)
main ( ) { cout << z;}
{ };
clrscr ( ) ; class A12 : public A1, public A2
result S1 ; {
S1.get_n (345) int r, t ;
S1.get_m (30, 35) ; public:
S1.get-S (7) ; void get (int a)
S1. show ( ); { r = a;}
} void show (void)
{t=x+y+z+r;
//Program to show hybrid inheritance using virtual base classes cout << “result =” << t ;
#include<iostream.h> }
#include<conio.h> };
Class A main ( )
{ {
clrscr ( ) ;

A12 r ; Pure Virtual Functions


r.A : : get (3) ;
r.A1 : : get (4) ; Generally a function is declared virtual inside a base class and we redefine it the derived classes. The
r.A2 : : get (5) ; function declared in the base class seldom performs any task.
r.get (6) ;
r . show ( ) ; The following program demonstrates how a pure virtual function is defined, declared and invoked
} from the object of a derived class through the pointer of the base class. In the example there are two
classes employee and grade. The class employee is base class and the grade is derived class. The
functions getdata ( ) and display ( ) are declared for both the classes. For the class employee the
functions are defined with empty body or no code inside the function. The code is written for the
grade class. The methods of the derived class are invoked by the pointer to the base class.

#include<iostream.h>
#include<conio.h>
class employee {
int code
char name [20] ;
public:
virtual void getdata ( ) ;
virtual void display ( ) ;
};
class grade: public employee
{
char grd [90] ;
float salary ;
public :
void getdata ( ) ;
void display ( );
};
void employee :: getdata ( )
{
}
void employee:: display ( )
{
}
void grade : : getdata ( )
{
cout<< “ enter employee‟s grade “;
cin>> grd ;
cout<< “\n enter the salary “ ;
cin>> salary;
}
void grade : : display ( )
{
cout«" Grade salary \n";
cout« grd« " "« salary« endl;
} // Global method, Base class object is passed by value void
void main ( ) somefunc (Baseobj)
{ {
employee *ptr ; obj.display();
grade obj ; }
ptr = &obj ;
ptr->getdata ( ) ; intmain()
ptr->display ( ) ; {
Base b(33); Derived
getche ( ) ;
d(45, 54);
}
Output somefunc(b);
enter employee‟s grade A somefunc(d); // Object Slicing, the member j of d is sliced off return0;
enter the salary 250000 }
Grade salary
A 250000 Output:
I am Base class object, i = 33 I am
Base class object, i = 45
Object Slicing:
We can avoid above unexpected behavior with the use of pointers or references. Object slicing
In C++, a derived class object can be assigned to a base class object, but the other way is not doesn‟t occur when pointers or references to objects are passed as function arguments since apointer
possible. or reference of any type takes same amount of memory. For example, if we change the global
method myfunc() in the above program to following, object slicing doesn‟thappen.
classBase { intx, y; };
// rest of code is similar to above void
classDerived : publicBase { intz, w; }; intmain() somefunc (Base&obj)
{ {
Derived d; obj.display();
Base b = d; //ObjectSlicing, z and w of d are slicedoff }
} // rest of code is similar to above

Object Slicing happens when a derived class object is assigned to a base class object, additional Output:
attributes of a derived class object are sliced off to form the base class object.
I am Base class object, i = 33
I am Derived class object, i = 45, j = 54
#include
<iostream>usingnamespac
We get the same output if we use pointers and change the program to following.
estd;
// rest of code is similar to above void
classBase
{ somefunc (Base*objp)
protected: {
inti; objp->display();
}
public: intmain()
Base(inta) { i = a; } {
virtualvoiddisplay() Base *bp = new Base(33);
{ cout << "I am Base class object, i = " << i << endl;} Derived *dp = new Derived(45,54); somefunc(bp);
}; somefunc(dp); // No Object Slicing
return0;
classDerived : publicBase }
{
intj;
public: Output:
Derived(inta, intb) : Base(a) { j = b; }
virtualvoiddisplay() I am Base class object, i = 33
{ cout << "I am Derived class object, i = " I am Derived class object, i = 45, j = 54
<< i << ", j = " << j<<endl; }
}; Object slicing can be prevented by making the base class function pure virtual there by disallowing
object creation. It is not possible to create the object of a class which contains a pure virtual method.

C++ Function Overriding

If base class and derived class have member functions with same name and arguments. If you create
an object of derived class and write code to access that member function then, the member function
in derived class is only invoked, i.e., the member function of derived class overrides the member
function of base class. This feature in C++ programming is known as function overriding.

Abstract Class

Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes are
used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must provide
definition to the pure virtual function, otherwise they will also become abstract class.

Characteristics of Abstract Class

1. Abstract class cannot be instantiated, but pointers and refrences of Abstract class type can be
Accessing the Overridden Function in Base Class From Derived Class created.
2. Abstract class can have normal functions and variables along with a pure virtualfunction.
To access the overridden function of base class from derived class, scope resolution operator ::. For 3. Abstract classes are mainly used for Upcasting, so that its derived classes can useits
example: If you want to access get_data() function of base class from derived class in above interface.
example then, the following statement is used in derived class. 4. Classes inheriting an Abstract Class must implement all pure virtual functions, or else they
will become Abstracttoo.
A::get_data; // Calling get_data() of class A.
Pure Virtual Functions
It is because, if the name of class is not specified, the compiler thinks get_data() function is calling
Pure virtual Functions are virtual functions with no definition. They start with virtual keyword and
itself.
ends with = 0. Here is the syntax for a pure virtual function,

virtual void f() = 0;

Example of Abstract Class

classBase //Abstract baseclass


{
public:
virtual void show()=0; //Pure VirtualFunction
};

class Derived:public Base


{
public:
void show()
{ cout << "Implementation of Virtual Function in Derived class"; }
};

int main()
{
Baseobj; //Compile TimeError
Base *b;
Derived d;
b = &d;
b->show();
}

Output : Implementation of Virtual Function in Derived class

In the above example Base class is abstract, with pure virtual show() function, hence we cannot
create object of base class.

Why can't we create Object of Abstract Class ?

When we create a pure virtual function in Abstract class, we reserve a slot for a function in the
VTABLE(studied in last topic), but doesn't put any address in that slot. Hence the VTABLE will be
incomplete.

As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of
object for such class and will display an errror message whenever you try to do so.

30 P.T.O

You might also like