4th Chapter Inheritance C++

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Chapter 4 Object inheritance and reusability

Inheritance
Inheritance is a process by which new classes called derived classes are created from existing classes
called base classes.The derived classes have all the features of the base class and the programmer can
choose to add new features specific to the newly created derived class.

Base classes and derived classes


The existing class from which another class is derived is known as base class and the new created class is
derived class.A base class may be a direct base class of a derived class,or an indirect

Defining derived class(specifying derived class):

General syntax:

Class derived_class_name:visibility mode base_class_name

 The colon(:)indicates that derived_class_name is derived from the base_class_name.


 The visibility_mode is optional ,if present,may be either private or public or protected.
The default visibility mode isprivate.
 Visibility mode specifies whether the features of the base class are privately derived or publicly
derived or derived on protected.

1
Derived class visibility
Base class visibility
Public derivation Private derivation Protected derivation

private Not inherited Not inherited Not inherited

protected protected Not inherited Not inherited

public public Private protected

Visibility mode
Private mode

When a base class is inherited by a derived class in private mode,public and protected members of base
class and therefore they are accessible only within derived class i.e the public and protected members
in base class act as private members for the derived class.The private members of the base class are not
inherited in derived class.

Public mode

When a base class is inherited by derived class in public mode,public members of base class becomes
public members for the derived class and protected members of the base class become protected
members for derived class.The private members of the base class are note inherited in derived class.

Protected mode

When a base class is inherited by derived class in protected mode,the public and protected members in
the base class become protected members for the derived class.The private members of the base class
are not inherited in derived class.

2
Types of inheritance

1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid inheritance

1.Single inheritance
When a single class is being inherited by a class,it is called single or simple inheritance.In other words,a
derived class with only one base class is called single inheritance.single inheritance is an ability of a
derived class to inherit the member functions and variables of the existing class.A derived class is
defined as following.

Syntax:

Class derived_class_name:visibility_mode base_class_name

Class body

};

Class A Base class

Class B
derived class

General form

Class A
{
……….
};
Class B:public A
{
}
Example1

3
#include<iostream>
using namespace std;
class person
{
protected:
char name[20];
int age;
public:
void readpersondata(){
cout<<"enter name";
cin>>name;
cout<<"enter age:";
cin>>age;
}
void displaypersondata(){
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
}
};
class employee:public person
{
private:
char designation[20];
float salary;
public:
void reademployeedata(){
readpersondata();
cout<<"enter designation:";
cin>>designation;
cout<<"enter salary:";
cin>>salary;
}
void displayemployeedata(){
cout<<"the record of employee is:\n";
displaypersondata();
cout<<"designation:"<<designation<<endl;
cout<<"salary:"<<salary<<endl;
}
};
int main(){
employee emp;

4
emp.reademployeedata();
emp.displayemployeedata();

return 0;
}

Example 2
#include<iostream>
using namespace std;
class A
{
int x;
protected:
int y;
public:
int z;
void getxyz(){
cout<<"enter value of x,y,z"<<endl;
cin>>x>>y>>z;
}
void showxyz()
{
cout<<"x="<<x<<"y="<<y<<"z="<<z<<endl;
}
};
class b:public A
{
private:
int k,sum;
public:
void get_k()
{
cout<<"enter value of k"<<endl;
cin>>k;
}
void show_k(){
cout<<"k="<<k<<endl;
}
void addition(){
sum =y+z+k;
}
void display(){

5
cout<<"sum =" <<sum<<endl;
}
};
int main(){
b b1;
b1.getxyz();
b1.get_k();
b1.show_k();
b1.addition();
b1.display();
return 0;
}

2.Multiple inheritance

It is a type of inheritance in which new class is created from more than one base class.In this type of
inheritance a single derived class uses behaviour of two base classes.

Syntax

Class A{

………………

Class B

………….

};

Class C:visibility _mode A,visibility_mode B{

…………….

6
Base class B Base class
A

C
Derived class

All data members in protected and public of class A and B can be accessed using object of classs C.here
two base classes A and B have been created and derived class c is created from both base classes.

Example

#include<iostream>
using namespace std;
class academicactivities{
protected:
float acd_total_marks;
public:
void readacdmarks(){
cout<<"enter total marks in exam";
cin>>acd_total_marks;
}
void displayacdmarks(){
cout<<"total academic mark is:"<<acd_total_marks<<endl;
}
};
class extraactivities
{
protected:
float discipline_marks;
float punctuality_marks;
public:
void readextramarks(){
cout<<"enter marks in discipline";
cin>>discipline_marks;
cout<<"enter marks in punctuality:";
cin>>punctuality_marks;
}

7
void displayextramarks(){
cout<<"marks in discipline:"<<discipline_marks<<endl;
cout<<"marks in punctuality:"<<punctuality_marks;
}
};
class result:public extraactivities,public academicactivities
{
float total_marks;
public:
void calculateresult(){
total_marks = acd_total_marks+discipline_marks +punctuality_marks;
}
void displayresult()
{displayacdmarks();
displayextramarks();
cout<<endl<<"total marks:"<<total_marks;
}
};
int main(){
result r;
r.readacdmarks();
r.readextramarks();
r.calculateresult();
cout<<endl<<"your record is"<<endl;
r.displayresult();
return 0;
}

8
Ambiguity in multiple inheritance
When two or more than two base classes have a function of identical name and when class inherits
from multiple base classes then ambiguity occurs.

Example

#include<iostream>

using namespace std;

class m
{
public:
void display()
{
cout<<" class m"<<endl;
}
};
class n{
public:
void display(){
cout<<"class n"<<endl;
}
};

class p:public m,public n


{public:
void display(){
m::display();
n::display();
}
};

int main(){
p p;
p.display();
return 0;
}

which display function is used by the derived class when we inherit these two classes?
we can solve this problem by redefining the member in the derived class using resolution operator with
the function as shown below.

9
Ambiguity in single inheritance

#include<iostream>

using namespace std;

class A
{public:
void display(){
cout<<"a"<<endl;
}
};
class B:public A{
public:
void display(){
cout<<"b"<<endl;
}
};
int main(){
B b;
b.display();
b.A::display();

b.B::display();

return 0;

In this case the function in the derived class overrides the inherited function and therefore a simple call

to display() by B type object will invoke function defined in B only.However,we may invoke the function

defined in A by using the scope resolution operator to specify the class.

10
2.Multilevel inheritance
In multilevel inheritance a class is derived from another derived class.Thus base class of a derived class is
also derived of another base class.An example

A
Base class

B
Derived class

Derived class from B


C
example

#include<iostream>
using namespace std;
class student{
private:
int roll;
public:
void getroll(){
cout<<"enter roll";
cin>>roll;

}
void displayroll(){
cout<<"roll:"<<roll<<endl;
}
};
class examination : public student{
protected: float subject1,subject2;
public:
void getmarks(){
cout<<"enter marks in first subject:";
cin>>subject1;
cout<<"enter marks in second subject:";
cin>>subject2;
}

11
void displaymarks(){
cout<<"marks in first subject:"<<subject1<<endl;
cout<<"marks in second subject:"<<subject2<<endl;
}
};
class result:public examination{
int total;
public:
void calculateresult(){
total = subject1 + subject2;
}
void displayresult(){
cout<<"total marks :"<<total;
}
};
int main(){
result r1;
r1.getroll();
r1.getmarks();
r1.calculateresult();
cout<<"-------record of student is-------"<<endl;
r1.displayroll();
r1.displaymarks();
r1.displayresult();
return 0;
}

4.Hierarchical inheritance
It is the process of deriving two or more classes form single base class.And in turn each of the derived
classes can further be inherited in same way.Thus it forms hierarchy of classes of a tree of classes which
is rooted at single class.

B C D

12
GENERAL FORM

Class A{

};

Class B:public A{

};

Class C:publc A{

};

Class D:Public A{

};

In general form three classes B and C and D are derived from same base class A.All data members in
protected and public of Class A can be accessed using object of classes B,C,D.

Example

#include<iostream>
using namespace std;
class person{
protected:
char name[20];
int age;
public:
void getperson(){
cout<<"enter name:";
cin>>name;
cout<<"enter age";
cin>>age;
}
void displayperson(){
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
}
};
class student:public person{
int roll;
float marks;

13
public:
void getstudent(){
cout<<"enter roll";
cin>>roll;
cout<<"enter total marks";
cin>>marks;
}
void displaystudent(){
cout<<"roll:"<<roll<<endl;
cout<<"total marks:"<<marks<<endl;
}
};
class employee:public person
{
char designation[20];
float salary;
public:
void getemployee(){
cout<<"enter designation:";
cin>>designation;
cout<<"enter salary";
cin>>salary;
}
void displayemployee()
{
cout<<"designation:"<<designation<<endl;
cout<<"salary:"<<salary<<endl;
}
};
int main(){
student s1;
cout<<"reading information of student"<<endl;
s1.getperson();
s1.getstudent();
cout<<"reading information of employee"<<endl;
employee e1;
e1.getperson();
e1.getemployee();
cout<<"displaying record of student"<<endl;
s1.displayperson();
s1.displaystudent();
cout<<"displaying record of employee"<<endl;

14
e1.displayperson();
e1.displayemployee();
return 0;
}

15
Hybrid inheritance
The use of more than one type of inheritance is called hybrid inheritance .It is used in such situations
where we need to apply two or more types of inheritance to design a program.

A Base class

Derived class of A c B Derived class of base class A

D
Derived class from C

E
Derived class from D

Example //hybrid inheritance

#include<iostream>
using namespace std;
class person{
protected:
char name[20];
int age;
public:
void getperson(){
cout<<"enter name:";
cin>>name;
cout<<"enter age";
cin>>age;
}
void displayperson(){
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
}
};
class student:public person{

16
int roll;
public: void getstudent(){
cout<<"enter roll:";
cin>>roll;
}
void displaystudent(){
cout<<"roll:"<<roll<<endl;
}
};
class employee:public person{
char designation[20];
float salary;
public:
void getemployee(){
cout<<"enter designation:";
cin>>designation;
cout<<"enter salary:";
cin>>salary;
}
void displayemployee()
{
cout<<"designation:"<<designation<<endl;
cout<<"salary:"<<salary<<endl;
}
};
class examination:public student{
protected:
float theory_marks,lab_marks;
public:
void getmarksinsubjects(){
cout<<"enter marks of student in theory exam:";
cin>>theory_marks;
cout<<"enter marks of student in lab exam:";
cin>>lab_marks;
}
void displaymarks()
{
cout<<"marks in theory exam:"<<theory_marks<<endl;
cout<<"marks in lab exam:"<<lab_marks<<endl;
}
};
class result:public examination{

17
private:
float total_marks;
public:
void calculatetotalmarks(){
total_marks = theory_marks + lab_marks;}
void displayresult(){
cout<<"total_marks:"<<total_marks<<endl;
if(total_marks>32)
{
cout<<"congratulation"<<endl;}
else
{cout<<"sorry try again"<<endl;
}
}};
int main(){
result rs;
cout<<"reading information of student"<<endl;
rs.getperson();
rs.getstudent();
rs.getmarksinsubjects();
employee emp;
cout<<"reading information of employee"<<endl;
emp.getperson();
emp.getemployee();
cout<<"displaying record……………."<<endl;
cout<<"the record of student…."<<endl;
rs.displayperson();
rs.displaystudent();
rs.calculatetotalmarks();
rs.displaymarks();
rs.displayresult();
cout<<"******************"<<endl;
cout<<"the record of employee….."<<endl;
emp.displayperson();
emp.displayemployee();
return 0;
}

18
Using constructors and destructors in derived classes
 The derived class need not have constructor as long as the base class need not have constructor
as long as the base class has no argument constructor.
 However if the base class has constructor with arguments(one or more),then it is mandatory of
the derived class to have a constructor and pass the arguments to the base class constructor.
 When an object of a derived class is created the constructor of the base class is executed first
and later the constructor of the derived class.
 In case of multiple inheritance ,the base class is constructed in the same order in which header
appear in the declaration of the derived class.
 Similarly in a multilevel inheritance,the constructor will be executed in the order of inheritance.
 The header line of the derived-constructor function contains two parts separated by a colon(:).
The first part provides the declaration of the arguments that are passed to the derived class
constructor and the second part lists the function calls to the base class.

General form of defining a derived constructor:


Derived constructor(arglist1,arglist2,…arglistn,arglist
d):Base1(arglist1),base2(arglist2)…..baseN(arglistN)

{
//body of derived constructor
}

Example
D(int a1,int a2,int b2,int d):A(a1,a2,),B(b1,b2)
{
d=d1;
}

Constructor in a multiple inheritance

#include<iostream>
Alpha Beta
using namespace std;
class alpha x y
{private:
int x;
public:
alpha(int i)
Gamma
{ x=i;
m, n
19
}
void show_x(){
cout<<"x="<<x<<endl;
}
};
class beta
{
private:
float y;
public:
beta(float j)
{
y =j;
}
void show_y(){
cout<<"y="<<y<<endl;
}
};

class gamma:public beta,public alpha{


private:
int m,n;
public:
gamma(int a,float b,int c, int d):alpha (a),beta(b){
m = c;
n =d;
}
void show_mn(){
cout<<"m ="<<m<<endl;
cout<<"n="<<n;
}};
int main(){

gamma g(5,7.6,30,100);
cout<<endl;
g.show_x();
g.show_y();
g.show_mn();
return 0;
}

20
Constructor in a multilevel inheritance
#include<iostream>
using namespace std;
class a
Alpha
{
public: Alpha(int nvalue)
a (int nvalue){
cout<<"a:"<<nvalue<<endl; show
}
};
class b: public a Beta
{
Beta(int nvalue, float
public: dvalue):a(nvalue)
b(int nvalue,float dvalue):a(nvalue)
{
cout<<"b:"<<dvalue<<endl;
}};
class c: public b{
public: Gamma
c(int nvalue,float dvalue,char chvalue):b(nvalue,dvalue)
{ Gamma(int
cout<<"c:"<<chvalue<<endl; ,float,char):b(nvalue,dval
}}; ue)
int main(){
c cclass(5,4.3,'r');
return 0;
}

21
Virtual base class in C++
Virtual classes are primarily used during multiple inheritance. To avoid, multiple instances of the same
class being taken to the same class which later causes ambiguity, virtual classes are used.

Class A

Class C
Class B

Class D

Consider the case where there is just one class A. Two other grades, B and C, descend from
this class A. The data members/functions of class A are inherited twice to class D, as seen in
the diagram. The first will take you through class B, and the second will take you through
class C. When an object of class D accesses any data or function member of class A, it's
unclear which data or function member would be named. One was inherited via B, and it
inherited the other via C. This throws the compiler into a loop and causes an error to
appear.

The duplication of inherited members due to these multiple paths can be avoided by
making common base class as virtual class while declaring the direct or intermediate base
classes.By making a class virtual only one copy of that class is inherited though we may
have many inheritance paths between the virtual base class and derived class.we can
speciy a base class inheritance by using the keyword virtual.

22
Constructor call in hybrid inheritance using virtual base classes.

college

Name,location

student teacher

Sname Tname
rol tcode

book

Bookname
Writername
bcode

23
#include<iostream>

#include<string.h>

using namespace std;

class college{

string name,location;

public:

college(string a,string b)

name =a;

location=b;

void display(){

cout<<"name of college:"<<name<<endl;

cout<<"location of college:"<<location<<endl;

};

class student:virtual public college{

string sname;

int roll;

public:

student(string a ,string b,string c,int d):college(a,b)

{sname = c;

roll =d;

void display(){

24
cout<<"name of student:"<<sname<<endl;

cout<<"roll of student:"<<roll<<endl;

};

class teacher :virtual public college{

string tname;

int tcode;

public:

teacher(string a,string b,string c,int d):college(a,b)

{ tname =c;

tcode = d;

void display(){

cout<<"name of teacher:"<<tname<<endl;

cout<<"code of teacher:"<<tcode<<endl;

};

class book:public student,public teacher{

string bookname;

string wname;

int bcode;

public:

book(string a,string b,string c,int d,string e,int t,string g ,string h,int i):student
(a,b,c,d),teacher(a,b,e,t),college(a,b){

bookname = g;

wname =h;

25
bcode =i;

void display(){

cout<<"the information you entered are"<<endl<<endl;

college::display();

student::display();

teacher::display();

cout<<"name of book:"<<bookname<<endl;

cout<<"code of book:"<<bcode<<endl;

cout<<"name of writer:"<<wname;

};

int main(){

book b("universal","patan","ram",44,"hari sir",75,"c++","bjarne",55);

b.display();

return 0;

alternative//Hybrid virtual inheritance using constructor


#include<iostream>

#include<string.h>

using namespace std;

class college{

string namecolg,location;

public:

college()

26
{

cout<<"enter the name of college"<<endl;

cin>>namecolg;

cout<<"enter the location of college"<<endl;

cin>>location;

void display(){

cout<<"name of college:"<<namecolg<<endl;

cout<<"location of college:"<<location<<endl;

};

class student:virtual public college{

string sname;

int roll;

public:

student():college(){

cout<<"entr the name of student"<<"\n";

cin>>sname;

cout<<"enter the roll of student"<<endl;

cin>>roll;

void display(){

27
cout<<"name of student:"<<sname<<endl;

cout<<"roll of student:"<<roll<<endl;

};

class teacher :virtual public college{

string tname;

int tcode;

public:

teacher():college(){

cout<<"enter the name of teacher"<<endl;

cin>>tname;

cout<<"enter the code of teacher"<<endl;

cin>>tcode;

void display(){

cout<<"name of teacher:"<<tname<<endl;

cout<<"code of teacher:"<<tcode<<endl;

};

class book:public student,public teacher{

string bookname;

string wname;

int bcode;

public:

book():student(),teacher(){

28
cout<<"etner the name of book"<<endl;

cin>>bookname;

cout<<"enter the name of bookcode"<<endl;

cin>>bcode;

cout<<"enter the name of writeer"<<endl;

cin>>wname;

void display(){

cout<<"the information you entered are"<<endl<<endl;

college::display();

student::display();

teacher::display();

cout<<"name of book:"<<bookname<<endl;

cout<<"code of book:"<<bcode<<endl;

cout<<"name of writer:"<<wname;

};

int main(){

book b;

b.display();

return 0;

29
Question :Implement following diagram in code.

Student

Name,roll

Void sget()

Void sdisplay()
Sports
Test
Price
marks
Void ssget()
Void tget()
Void ssdisplay()
Void tdisplay()

Result

Fee

Void rget()

Void rdisplay()

#include<iostream>

using namespace std;

class student{

int roll;

string name;

public:

void sget(){

cout<<"enter name";

cin>>name;

cout<<"enter roll";

30
cin>>roll;

void sdisplay(){

cout<<"name is "<<name<<endl;

cout<<"your roll"<<roll<<endl;

}};

class test:virtual public student{

float marks;

public:

void tget(){

cout<<"enter marks";

cin>>marks;

void tdisplay(){

cout<<"your marks is"<<marks<<endl;

};

class sports:virtual public student{

int price;

public:void ssget(){

cout<<"enter your price";

cin>>price;

void ssdisplay(){

cout<<"price is"<<price<<endl;

31
}

};

class result: public test,public sports{

int fee;

public:

void rget(){

sget();

tget()

ssget();

cout<<"enter fees"<<endl;

cin>>fee;

void rdisplay(){

sdisplay();

tdisplay();

ssdisplay();

cout<<" fee is "<<fee;

}};

int main(){

result r;

r.rget();

r.rdisplay();

return 0;

32
Containership or nested class
Containership is technique in which one class contains object of another class as member data.The class
which contains the object cannot access any protected or private members of the contained class.The
relationship between the container and the contained object is “has- a “ instead of “is-a”.

Question.define a class birthday with members:day,month and year.Use object of this class as member
of another class employee to read and display name and date of birth of an employee.

#include<iostream>
using namespace std;
class birthday
{
int day;
int month;
int year;
public:
void getbirthday();
void displaybirthday();
};
void birthday::getbirthday(){
cout<<"enter day:";
cin>>day;
cout<<"enter month";
cin>>month;
cout<<"enter year";
cin>>year;
}
void birthday::displaybirthday(){
cout<<day<<"/";
cout<<month<<"/";
cout<<year<<endl;
}
class employee{
char name[20];
birthday dob;
public: void getperson();
void displayperson();
};
void employee::getperson(){
cout<<"enter name:";
cin>>name;

33
cout<<"enter data of birth:"<<endl;
dob.getbirthday();
}
void employee::displayperson(){
cout<<endl<<"----------------------------------------"<<endl;
cout<<"name:"<<name<<endl;
cout<<"date of birth:";
dob.displaybirthday();
}
int main(){
employee emp;
cout<<"enter information of an employee:"<<endl;
emp.getperson();
cout<<"your entered information :"<<endl;
emp.displayperson();
return 0;
}

The has a rule and the is a rule of abstraction


Has a relationship.The has a relationship is reverse of part of relationship.when a class consists of
another class as its element.It depicts the has a relationship .when you include the address of
passenger,the relationship between the passenger and address class reads as the student class has an
address.The has a relationship is also known as aggregation of composition.The object oriented
programming supports division into various components when we increased the specialized abstraction
or real world components.This is commonly known as is a and has a abstraction.The whole task is
divided into various parts increase an abstraction.Similarly,”a car has an engine” and “a bus has an
engine”,In such,abstraction engine is common type.But the two objects have specialized in term of
engine,s variation.The both objects cannot use the same engine super class properties to the car and
bus clases because we cannot use the same engine in both classes.there is different relationship
between the components,which can easily understand and apply object oriented techniques among
them.

34
Difference between is-a rule and has-a rule

Is a relationship Has a relationship

1.if thesecond concept is a component of the first


1.if the first concept is a specialized instance of the
and the two are not in any sense the same thing
second one then there exists an is –a relationship
then there exists a “has –a” relationship between
between them.
them.

2.example: 2.example
Car is a vehicle Car has a engine

3.”Has A “ relationship refers to composition.


3.is a relationship refers to inheritance.

4.is –a relationship assers the instance of the 4.in “has-a” relationship class contains object of
subclass must be more specialized form of the another class as its member data to make it as a
superclass. whole.

5.class vehicle{ 5.class engine


}; {
Class car:public vehicle{ };
}; Class car{
Class Bus:public vehicle{ Engine e;// a car is composed of an engine
}; };

35
Difference between inheritance and composition

S.N INHERITANCE COMPOSITION

1. In Inheritance derived classes inherit In composition a class contains object of


attributes and methods from their parent another class as its member data
class.

2. it exhibits “is-a “ relationship It exhibits “has-a” relationship

3. Example car is a vechicle Example:car has a engine

4. Class vechicle{ Class engine{


}; };
Class car:public vehicle{ Class car{
}; Engine e;
Class bus:public vehicle{ //a car is composed of an engine}
}; ;

5. Inheritance leads tight coupling between In composition relationship between class


super class and subclass.so it is harder to can be decoupled easily.so it can be easily
maintain in future. maintained in future.

6. Inheritance permits polymorphism Composttion doesnot permit


polymorphism

7 Example program of single inheritance 7.example program of composition

36
Constructor and destructor in destructor in inheritance
 Compiler automatically calls constructor of base class and derived class automatically when
derived class object is created.
 If we declare derived class object in inheritance constructor of base class is executed first and
then constructor of derived class.
 If derived class object goes out of scope or deleted by programmer the derived clas destructor is
executed first and then base class destructor.

Illustration of when base and derived class constructor and destructor functions are executed.

#include<iostream>
using namespace std;
class a
{
public:
a(){
cout<<"constructor in base class"<<endl;
}
~a()
{
cout<<"destructor in base class"<<endl;}
};
class b:public a
{
public:b(){
cout<<"constructor in derived class"<<endl;
}
~b(){
cout<<"destructor in derived class"<<endl;
}};
int main(){
b obj;
return 0;
}
Output
Constructor in base class
Constructor in derived class
Destructor in derived class
Destructor in base class

37
Subclass,subtype and principle of substitutability
If we consider the relationship of a data type assosciated with a parent class to the data type associated
with a child class ,the following observations can be made.

 Instances of the child class must possess all the data members associated with the parent class.
 instances of the child class must implement,through inheritance as least(if not explicitly
overridden),all functionality defined for parent class.(They can also define new functionality).
 The instance of a child class can mimic the behavior of parent class and should be
indistinguishable from an instance of parent class if substituted in similar situation.

The principle of substitutability


It states that “if we have two classes A and B such that class B is a subclass of A,it should be possible to
substitute instances of class B for instances of class A in any situation with no observable effect”.

The term subtype is used to refer to a subclass relationship in which the principle of substitutability is
maintained to distinguish such forms from the general subclass relationship,we may or may not satisfy
this principle.

In the example below class B object is replaced by the object of class A withour any error.

This is achieved when a child class is inherited from a base class publicly.In the same example,if the
mode of inheritance is made private the base class object ‘a’ cant be replaced by the parent class object
‘a’.

38
Software reusability
Software reusability is the practice of using existing code for a new software.But in order to reuse
code,that needs to be high quality.And that means is should be safe,secure,reliable efficient and
maintainable.

In OOP,the concept of inheritance provide the idea of reusability.This means that we can add additional
features to an existing class without modifying it.This is possible by deriving a new class from the
existing one.The new class will have the combined features of both the classes.Resusability can be
provided through the concept of composition also.In composition also.In composition one class contains
the object of another classes to make it as a whole.

Advantages of reusability.
 Re usability enhanced reliability.
 Re usability saves the programmer time and effort.
 As the existing code is reused ,it leads to less development and maintenance costs.
 Extensibility as we can extend the already made classes by adding some new features.
 Inheritance makes the sub classes follow a standard interface.

Difficulty in software reusability


 As the number of projects and developers increases,it becomes harder to re use software .Is a
challenge to effectively communicate the details and requirements for code reuse.
 As the number of projects and developers grows,its difficult to share libraries of resusable code.

Forms of inheritance

1.subclassing for specialization


 The new class is specialized form of parent class but satistifies the specifications of the parent
class in all relevant aspects.
 Window class provides the general windowing operations(moving,resizing,iconification ans so
on).
 The specialized subclass TextEditWindow inherits the window operations and in addition
provides the facilities that allow window to display textual material and user to edit the text
values.

2.subclassing for specification


 The parent class defines behavior that will be implemented in the child class.The inheritance for
specification can be recognized when a parent class does not implement actual behavior but it
defines how the behavior will be implemented in the child classes.For instance when we
declared protected member function in the parent class this member can access only one level
to the derived.Therefore inheritance specifies the behaviors of child classes and its member
items.

39
3.Subclassing for construction:
The child class can be constructed from parent class with implementing various access specifiers.The
desired behavior from the base class can be called and construct in the child class.some arguments and
behaviors provided by the parent class may redesign inside the sub class construction.Inheritance
provides the facility to construct new class with the help of parent class.Therefore parent class provides
some construction guidelines to the child class/sub class.

4.Sub classing for generalization


In some time child class modify the methods of the parent class.It is applicable when we design child
class from existing base class.The child class modifies or override(replace) some method of the parent
class.A child class can use the general behavior of the parent class.sub classing for generalization is the
opposite to sub classing for sepecification.When we are inheriting the general propertied of the parent
class can be easily accessible to the child.The child class holds the common protperties that will redefine
in the base class.Like as mother and son properties of aboce code(upcasting).

5.Sub classing for extension


The subclass for extension adds new functionality to child class while designing new child class.The
inheritance provides better possibility to add new function of their parent other than parent class
has.The child class adds new functionality but does not change any inherited behaviors.So child class is
look like as extension part of base class because child classes are accessing some properties from parent
class.

6.sub classing for limitation


The subclass for limitation occurs when the behaviors of subclass are similar or more dependent to the
behavior of parent class.Subclass for limitation occurs when we define some restricted properties.In
sometime the child class restricts the use of behaviors and functions parent class(say public properties
of base class can be easily inherited to derived class but when inheriting private properties of parent
class cannot be inherited to the child class.

7.sub classing for variance


The child class and parent class are different in nature when the level of inheritance increased and
relationship between them are imaginary .When we increased the level of inheritance.Therefore large
varieties of subclasses established the relationship with their parent classes.

8.sub classing for combination


The child class inherits the properties from more than one class.The child class has coexistence only
from base class.So child class exists only from base class.Inheritance provides the facility to combine
variety of classes according to their nature,behavior and user requirement.

40
Benefits of inheritance
 Software reusability.The software reusability is very useful concept while developing new
software product with the help of previous components.Therefore some code should not be
rewrite;we just reused predefined behaviors from super class to the derived class.The behavior
of inheritance increases productivity of software designer,because the programmers do not
spend much time to rewrited the same code,that has been written and tested before.
 Code sharing:inheritance provides code sharing in several levels of object oriented design;
Many users can share same parent class properties while designing the derived class for specific
task.
 Polymorphishm:polymorphism in programming language permits the programmer to design
high level resusable component that can be suitable for different application design.
 Information hiding:The programmer who resuses the software component needs only to
understand behaviors of particular component that interact with other components.Through
the use of private,protected and public visibility specifies the program become more
secured.The inheritance provides some data items are more secured and put some restriction to
use in the derived clases.
 Rapid prototyping:while inheriting super class properties we can reused the same code and
developed new component easily.This process reduces coding time and logic is known as rapid
prototyping.With the help of inheritance software system can be design more quickly and
easily.Therefore inheritance increased software prototype because the component that behave
exactly what we required had already done before.

41

You might also like