Unit 3
Unit 3
Inheritance:
Reaccessability is yet another feature of OOP's. C++ strongly supports the concept of reusability.
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
the properties of existing ones. The mechanism of deriving a new class from an old one is called
'INHERTTENCE'. This is often referred to as IS-A' relationship because very object of the class
being defined "is" also an object of inherited class. The old class is called 'BASE' class and thenew
one iscalled'DERIEVED'class.
Defining DerivedClasses
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:
// members of derivedclass
};
The colon indicates that the a-class name is derived from the base class name. The access specifier or
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.
Single Inheritance
When a class inherits from a single base class, it is known as single inheritance. Following program
shows the single inheritance using public derivation.
#include<iostream.h>
#include<conio.h>
class worker
{
int age;
char name [10];
public:
void get ( );
};
void worker : : get ( )
{
cout <<”yout name please”
cin >> name;
cout <<”your age please” ;
cin >> age;
}
void worker :: show ( )
{
cout <<”In My name is :”<<name<<”In My age is :”<<age;
}
class manager ::publicworker //derived class(publicly)
{
int now;
public:
void get ( ) ;
void show ( ) ;
};
void manager : : get ( )
{
worker : : get (); //the calling of base class input fn.
cout << “number of workers underyou”;
cin >> now;
cin>>name>>age;
} ( if they were public )
void manager :: show ()
{
worker :: show(); //calling of base class o/pfn.
cout <<“in No. of workers under me are: “ << now;
}
main ( )
{
clrscr ( ) ;
worker W1;
manager M1;
M1 .get ( );
M1.show ( ) ;
}
If you input the following to this program:
Your name please
Ravinder
Your age please
27
number of workers under you
30
Then the output will be as follows:
My name is : Ravinder
My age is : 27
No. of workers under me are : 30
The following program shows the single inheritance by private derivation.
#include<iostream.h>
#include<conio.h>
classworker //Base classdeclaration
{
int age;
char name [10] ;
public:
void get ( ) ;
void show ( ) ;
};
void worker : : get ( )
{
cout << “your name please” ;
cin >> name;
cout << “your age please”;
cin >>age;
}
void worker : show ( )
{
cout << “in my name is: “ <<name<< “in” << “my age is : “ <<age;
}
class manager : worker //Derived class (privately by default)
{
int now;
public:
void get ( ) ;
void show ( ) ;
};
void manager : : get ( )
{
worker : : get ( ); //calling the get function of base
cout << “number of worker under you”; class which is
cin >> now;
}
void manager : : show ( )
{
worker : : show ( ) ;
cout << “in no. of worker under me are : “ <<now;
}
main ( )
{
clrscr ( ) ;
worker wl ;
manager ml;
ml.get ( ) ;
ml.show ( );
}
The following program shows the single inheritance using protected derivation
#include<conio.h>
#include<iostream.h>
classworker //Base class declaration
{ protected:
int age; char name [20];
public:
void get ( );
void show ( );
};
void worker :: get ()
{
cout >> “your name please”;
cin >>name;
cout << “your age please”;
cin >> age;
}
void worker :: show ( )
{
cout << “in my name is: “ << name << “in my age is “ <<age;
}
class manager:: protected worker // protected inheritance
{
int now;
public:
void get ();
void show ( ) ;
};
void manager : : get ( )
{
cout << “please enter the name In”;
cin >> name;
cout<< “please enter the age In”; //Directly inputting thedata
cin>>age; members of baseclass
cout << “ please enter the no. of workers under you:”;
cin >> now;
}
void manager : : show ( )
{
cout « "your name is : "«name«" and age is : "«age;
cout «"In no. of workers under your are : "«now;
main ( )
{
clrscr ( ) ;
manager ml;
ml.get ( ) ;
cout « "\n \n";
ml.show ( );
}
The below mentioned table summarizes how the visibility of members undergo modifications when
they are inherited
A Base class
C
Derived class
#include<iostream.h>
#include<conio.h>
classworker // Base classdeclaration
{
int age;
char name [20] ;
public;
void get( ) ;
void show( ) ;
}
Private:
int age;
char name[20];
Protected:
Private:
int age;
char name[20];
Manager:Worker
Private:
int now;
Protected:
Public:
void get()
void show()
worker::get()
worker::get()
Ceo: Manager
Public:
Protected:
Public:
All the inherited
members
Multiple Inheritances
A class can inherit the attributes of two or more classes. This mechanism is known as „MULTIPLE
INHERITENCE‟. Multiple inheritance allows us to combine the features
of several existing classes as a starring point for defining new classes. It is like the child inheriting the
physical feature of one parent and the intelligence of another. The syntax of the derived class is
asfollows:
Where the visibility refers to the access specifiers i.e. public, private or protected. Following program
shows the multipleinheritance.
#include<iostream.h>
#include<conio . h>
classfather //Declaration of baseclassl
{
int age ;
char flame [20] ;
public:
void get ( ) ;
void show ( ) ;
};
void father : : get ( )
{
cout << “your father name please”;
cin >> name;
cout << “Enter the age”;
cin >> age;
}
void father : : 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 ;
public:
void get ( )
{
cout << “mother‟s name please” << “In”;
cin >> name;
cout << “mother‟s age please” << “in”;
cin >> age;
}
void show ( )
{
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
intstd;
public:
void get ( ) ;
void show ( ) ;
};
void daughter :: get ( )
{
father :: get ( ) ;
mother :: get ( ) ;
cout << “child's name: “;
cin >> name;
cout << “child's standard”;
cin >> std;
}
void daughter :: show ()
{
father :: show ();
nfather :: show ( ) ;
cout << “In child‟s name is : “ <<name;
cout << “In child's standard: “ << std;
}
main ( )
{
clrscr ( ) ;
daughter d1;
d1.get ( ) ;
d1.show ( ) ;
}
Diagrammatic Representation of Multiple Inheritance is asfollows:
Father Mother
Private: Private:
int age; int age;
char name[20]; char name[20];
Protected: Protected:
Public: Public:
void get() void get()
void show() void show()
Protected:
Public:
//self
void get(); void showQ;
//from Father
void get(); void show();
//from Mother
void get(); void show();
Hierarchical Inheritance
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
one level are shared by many others below that level for e.g.
Accounts
Fixed deposit
Class A
{
// body A
}
Class C: public A
Class B: public A {
{ //body B
//body B }
}
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.
{
father :: get ( ) ;
cout << “your (son) name please” << “in”; cin >>name;
cout << “your age please” << “ln”; cin>>age;
}
void son :: show ( )
{
father : : show ( ) ;
cout << “In my name is : “ <<name;
cout << “In my age is : “ <<age;
}
class daughter :publicfather //derived class2.
{
char name [15] ;
int age;
public:
void get ( )
{
father : : get ( ) ;
cout << “your (daughter‟s) name please In” cin>>name;
cout << “your age please In”; cin >>age;
}
void show ( )
{
father : : show ( ) ;
cout << “in my father name is: “ << name << “
In and his age is : “<<age;
}
};
main ( )
{
clrscr ( ) ;
son S1;
daughter D1 ;
S1. get ( );
D1. get ( ) ;
S1 .show( ) ;
D1. show ( ) ;
}
Hybrid Inheritance
There could be situations where we need to apply two or more types of inheritance to design a
program. Basically Hybrid Inheritance is the combination of one or more types of the inheritance.
Here is one implementation of hybrid inheritance.
public :
void get_m (int x, int y) {
parti = x; part 2 = y; }
void put_m (void) {
cout << “marks obtained: “ << “In”
<< “Part 1 = “ << part1 << “in”
<< “Part 2 = “ << part2 << “In”;
}
};
classsports // base forresult
{
protected : int score;
public:
void get_s (int s){
score = s }
void put_s (void){
cout << “ sports wt. : “ << score << “\n\n”;
}
};
class result : public test, public sports //Derived from test
&sports
{
int total;
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 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.
The duplication of the inherited members can be avoided by making common base class as the
virtual base class: fore.g.
classg_parent
{
//Body
};
class parent1: virtual public g_parent
{
// 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.
protected:
int y ;
public:
void get (int) ;
void show (void);
};
void A1 :: get (int a)
{ y = a;}
void A1 :: show (void)
{
cout <<y ;
{
class A2 : Virtual public A
{
protected:
int z ;
public:
void get (int a)
{ z =a;}
void show (void)
{ cout << z;}
};
class A12 : public A1, public A2
{
int r, t ;
public:
void get (int a)
{ r = a;}
void show (void)
{t=x+y+z+r;
cout << “result =” << t ;
}
};
main ( )
{
clrscr ( ) ;
A12 r ;
r.A : : get (3) ;
r.A1 : : get (4) ;
r.A2 : : get (5) ;
r.get (6) ;
r . show ( ) ;
}
Pure Virtual Functions
Generally a function is declared virtual inside a base class and we redefine it the derived classes. The
function declared in the base class seldom performs any task.
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;
}
void main ( )
{
employee *ptr ;
grade obj ;
ptr = &obj ;
ptr->getdata ( ) ;
ptr->display ( ) ;
getche ( ) ;
}
Output
enter employee‟s grade A
enter the salary 250000
Grade salary
A 250000
Object Slicing:
In C++, a derived class object can be assigned to a base class object, but the other way is not
possible.
classBase { intx, y; };
Object Slicing happens when a derived class object is assigned to a base class object, additional
attributes of a derived class object are sliced off to form the base class object.
#include
<iostream>usingnamespac
estd;
classBase
{
protected:
inti;
public:
Base(inta) { i = a; }
virtualvoiddisplay()
{ cout << "I am Base class object, i = " << i << endl;}
};
classDerived : publicBase
{
intj;
public:
Derived(inta, intb) : Base(a) { j = b; }
virtualvoiddisplay()
{ cout << "I am Derived class object, i = "
<< i << ", j = " << j<<endl; }
};
// Global method, Base class object is passed by value void
somefunc (Baseobj)
{
obj.display();
}
intmain()
{
Base b(33); Derived
d(45, 54);
somefunc(b);
somefunc(d); // Object Slicing, the member j of d is sliced off return0;
}
Output:
I am Base class object, i = 33 I am
Base class object, i = 45
We can avoid above unexpected behavior with the use of pointers or references. Object slicing
doesn‟t occur when pointers or references to objects are passed as function arguments since apointer
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.
Output:
We get the same output if we use pointers and change the program to following.
Output:
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.
To access the overridden function of base class from derived class, scope resolution operator ::. For
example: If you want to access get_data() function of base class from derived class in above
example then, the following statement is used in derived class.
It is because, if the name of class is not specified, the compiler thinks get_data() function is calling
itself.
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.
1. Abstract class cannot be instantiated, but pointers and refrences of Abstract class type can be
created.
2. Abstract class can have normal functions and variables along with a pure virtualfunction.
3. Abstract classes are mainly used for Upcasting, so that its derived classes can useits
interface.
4. Classes inheriting an Abstract Class must implement all pure virtual functions, or else they
will become Abstracttoo.
Pure virtual Functions are virtual functions with no definition. They start with virtual keyword and
ends with = 0. Here is the syntax for a pure virtual function,
int main()
{
Baseobj; //Compile TimeError
Base *b;
Derived d;
b = &d;
b->show();
}
In the above example Base class is abstract, with pure virtual show() function, hence we cannot
create object of base 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