0% found this document useful (0 votes)
5 views10 pages

C++ Unit-6

This chapter discusses inheritance in object-oriented programming, particularly in C++, detailing its types, such as single, multilevel, multiple, hierarchical, and hybrid inheritance. It explains how constructors and destructors work in derived classes, the visibility modifiers (public, protected, private), and the implications of these modifiers on inherited members. Additionally, it outlines the benefits of inheritance, including code reusability and hierarchical classification.

Uploaded by

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

C++ Unit-6

This chapter discusses inheritance in object-oriented programming, particularly in C++, detailing its types, such as single, multilevel, multiple, hierarchical, and hybrid inheritance. It explains how constructors and destructors work in derived classes, the visibility modifiers (public, protected, private), and the implications of these modifiers on inherited members. Additionally, it outlines the benefits of inheritance, including code reusability and hierarchical classification.

Uploaded by

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

Inheritance

This chapter deals with inheritance and its types. It explains the use of constructors and destructors in
derived classes. It also highlights on the merits and demerits of inheritance.

Introduction
OOPs provides us with a facility to reuse the things that already exists rather than creating the same all over
again. This saves time and increases reliability. C++ helps to reuse the class that has already been tested,
debugged thereby reducing the effort of developing and testing again. The reusability of class can be made
possible by creating new classes reusing the properties of the existing ones. Inheritance is the process of
creating new classes, called derivedclasses from the existing or base class. The derived class not only
inherits all the capabilities of the base class but also have it own unique properties. The base class remains
unchanged by this process.

Defining Derived Class


A derived class can be defined by specifying its relationship with the base class in addition to its own details.
Syntax

class derived_class_name: visibility_mode base_class_name


{
---// members of derived class
};
Where
Class — keyword to create a new class
Derived_class_name — name of the new class, which will inherit the base class
The colon (:) shows that the derived_class_name inherits the features of base_class_name.
Access-specifier (visibility_mode ) — either of private, public or protected. If neither is specified, PRIVATE
is taken as default
Base-class-name — name of the base class
Note: A derived class doesn’t inherit access to private data members. However, it does inherit a full parent
object, which contains any private members which that class declares.
Example 6.1:
1.class abc: private ABC // private derivation
{ members of abc };

2.class abe: public ABC // public derivation


{ members of abc };

3.class abc: protectedABC //(protected derivation


{ members of abc };

4. class ABC: XYZ //private derivation by default


{ };

While inheriting any sub-class from a base-class following things should be clearly understood:-

1. When a base class is privately inherited by a derived class, public member of base class becomes
private member of derived class and therefore, the public members of base class can only be
accessed by the member functions of derived class. This means theyare inaccessible by the objects of
the derived class.
1
2. When a base class is publicly inherited, the public members of base class becomes also the public
members of derived class. This means they are accessible to objects of derived class.
3. Whether the base class is inherited publicly or privately, the private members of base class are never
inherited and therefore, private members of base class will never become members of derived class.

Types of Inheritance
Following are different types of inheritance:-
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance

1.Single Inheritance:
The mechanism of deriving a class from only one base class is called single Inheritance.

Base class
A

B
Example 5.2:
//Program to depict single inheritance where a base class is publically derived class.
#include<iostream.h> void show(){
#include<conio.h> cout<<”\nb=”<<b;
class A{ cout<<”\nc=”<<c;
int a; //private data that cannot be inherited }
public: };
int b; //can be inherited int main(){
void input_ab() { B x;
cout<<”enter two number:”; x.input_ab();
cin>>a>>b; x.calc();
} x.show();
int get_a() { getch();
return a; return 0;
} };
class B:public A{
Output:
int c;
public: Enter two number:20 10
void calc(){
c=b*get_a(); B=10
}
C=200

In above e.g., Class B is derived publicly from class A. Thus the object x of the derived class can access all
the public members i.e. b, input_ab(), and get_a() of class A. But the private data 'a' cannot be inherited by
B. Thus class B will have more members than what is contains at the time of declaration. Also data member
'a' of class A is private and cannot be inherited. But the objects of B are able to access it through an
inherited member function of A.

Example 6.3:
// program to depict single inheritance where a base class is privately inherited by derived class.

2
#include<iostream.h> int A:: get_a()
#include<conio.h> {
using namespace std; return a;
class A }
{ void B:: calc()
int a; {
public: input_ab();
int b; c=b* get_a(); //a cannot be used directly
void input_ab(); }
intget_a(); void B:: show(){
}; cout<<"b="<<b<<"\nc="<<c;
class B: private A }
{ int main() Output:- {
int c; B x;
public: x.calc(); Enter two number: 20
void calc(); x.show(); 10
void show(); getch();
}; return 0; B=10
void A:: input_ab() } C=200
{
cout<<"Enter values for a and b:";
cin>>a>>b;
}

In above example, the base class A is privately inherited, so public members of base class A input_ab(), get
a()and b will be the private members of derived class B. Thus the derived class cannot directly access them
using its object. However the public member functions calc() and show () of class B can access them like
normal function and data.

Visibility Modifier
Visibility modifiers define the way in which the public members of a base class will be visible to the derived
class. Ultimately there are three visibility modifiers in C++:
1. Public
2. protected
3. private

The first two modifiers have already been described in previous chapters
Public Mode: If we derive a subclass from a public base class. Then the public member of the base class
will become public in the derived class and protected members of the base class will become protected in the
derived class.
Protected Mode: If we derive a subclass from a Protected base class. Then both public members and
protected members of the base class will become protected in the derived class.
Private Mode: If we derive a subclass from a Private base class. Then both public members and protected
members of the base class will become Private in the derived class.

Note: The private members in the base class cannot be directly accessed in the derived class, while
protected members can be directly accessed.
Protected

3
We know that, the private members of a base class cannot he inherited to the derived class. This means they
are not available for the derived class. Now there could be a situation where the derived class might require
the private data of base class. In such situation we can modify the visibility modifier of the private member
to protected. When a member is declared as protected, it is accessible by the member functions within its
class and any class immediately derived from it. It is not accessible to functions outside these classes.

Example 6.4:
class sample
{
private: //optional
----------------------- //visible to member functions within its class.
protected: //visible to member functions of its class and
---------------------- //immediate derived classes
public:
---------------------- //visible to all functions in the program.
};

Following table summarizes how the visibility of base class members undergoes modifications in all 3 types
of derivation.

Base class visibility Derived class visibility


Public derivation Private derivation Protected derivation
Private Not inherited Not inherited Not inherited
Protected Protected Private Protected
Public Public Private Protected

The private and protected members of a class can be accessible to following functions.
(a) A function that is a friend of class
(b) A member function that is a friend of class
(c) A member function of a derived class
The diagrammatic representation of above table is given below:
Class B
Not inheritable (X) Not inheritable (X)
Private
Protected
Public

Class D1:public B class D2:private B


Private Private
Protected Protected
Public Public

Class x:public D1,protected D2

Private
Protected
Public

4
2. Multi-level Inheritance
The mechanism of deriving a class from another 'derived class' is called multilevel inheritance In the figure,
class B is derived from class A and class C is again derived from B. Thus class B provides a link for
inheritance between A and C and hence it is called intermediate base class.

Example 6.5:
#include<iostream.h> void showmarks() {
#include<conio.h> cout<<"\nChemistry="<<m1<<"\nEnglish="<<
class info { m2; }
int roll; };
public: class tot: public marks {
void getroll() { int total;
cout<<"\nEnter roll no:"; public: void calc() {
cin>>roll; total= m1+m2;
} }
void showroll() { void showtot()
cout<<"\nRoll { cout<<"\nTotal marks="<<total; }
no="<<roll; };
} int main()
}; {
class marks: public info { tor x; Output:-
protected: int m1, m2; x.getroll();
Enter roll no:1
public: x.getmarks(); Enter marks in chemistry and
void getmarks() { x.calc(); English:67 80
cout<<"\nEnter marks in x.showroll();
chemistry and english:"; x.showmarks(); Roll no =1
cin>>m1>>m2; x.showtot(); Chemistry=67
} getch(); English=80
return 0; Total marks:147
}

In the above e.g., class marks inherits the class info publicly. Thus the public members of class info become
public members of class marks. Similarly class tot is derived publicly from class marks. This means public
members of marks also become public members of class tot. Hence we can conclude that public members
of class info also become the public members of class tot.
5
3. Multiple Inheritance
A class can inherit the attributes of two or more classes. This is called multiple inheritance. It allows us to
combine the features of several existing classes as a starting point for defining new classes. It is like a child
inheriting the physical features of one parent and the intelligence of another.
Example 6.6:
//Program to demonstrate Multiple Inheritance
#include<iostream.h>
#include<conio.h>
class A{
protected: int x;
public:
void get_x(){
cout<<"enter value of x";
cin>>x;}
};
class B {
protected: int y;
public:
void get_y() {
cout<<"enter value of y:";
cin>>y;}
};
class C {
protected: int z;
public: void get_z(){
cout<<"enter value of z:";
cin>>z;
}
};
class D: public A, public B, public C { protected: int total;
public:
void calc()
{ total=x+y+z; }
void show()
{ cout<<endl<<x<<" "<<y<<" Output:- "<<z;
cout<<"\ntotal="<<total;
} Enter value of x:10
}; Enter value of z:30
int main() Enter value of y:20
{ clrscr();
D k; 10 20 30
k.get_x(); Total:60
k.get_y();
k.get_z();
k.calc();
6
k.show();
getch();
return 0;
}

4. Hierarchical Inheritance
The mechanism of deriving more than one derived classes from a single base class is known as hierarchical
inheritance. Such type of inheritance is used to add additional members or enhance the capabilities of a
class.

TO

Figure 7.5: Hierarchical Inheritance example

Figure 7.6: Hierarchical Inheritance

In above figure, class A is the base class at higher level whose common features are shared I the derived
classes at lower level. Following is another e.g. of hierarchical inheritance:

Example 7.7:

//Program to demonstrate Hierarchical Inheritance

5. Hybrid Inheritance
This is another type of inheritance where a program is designed by combining two or more types of
inheritances. This type of inheritance can be a combination of single and multilevel inheritance, or multi -
level and hierarchical inheritance, or multiple or hierarchical inheritance and so on.

{ protected: int roll; public: void getroll(int r)

moalbum roll= void showroll() cout<<"Roll no:"<<roll<<endl;

Figure 7.7: Multilevel, multiple inheritance

Figure 7.8: Hierarchical, multiple inheritance

Fixample 7.8:

#include<conio.h> // Program to demonstrate hybrid inheritance #include<iostream.h>molamindem di


bomist
7
class student

void

Sports weightage =10

Total score=160.5

Constructors in Derived class


We know that constructors are the special member functions used for initializing the data elements of class.
Constructors can also be used in inheritance. Before using a constructor there are certain things that need to
be understood:
1. If there is base class constructor with no arguments then it is necessary to have constructor in derived
class.
2. If the base class constructor contains one or more argument, then it is compulsory for the derived
class to have constructor.
3. While implementing inheritance, we usually create objects of derived class. So the derived class is
responsible for passing arguments to the base class constructor. The derived class constructor
receives the entire argument list and passes them to base constructors in the order in which they are
declared in derived class.
4. The base class constructor is executed before executing derived class constructor.
5. In case of multiple inheritance, base classes are constructed in the order in which theyappear in
declaration of derived class.
6. In case of multi-level inheritance, the constructors are constructed in the order of inheritance.

The general syntax for defining derived class constructor is:

Derived_Constructor (Arglist1, Arglist2... … …ArglistN, ArglistD):Basel (arghstl),Base2 (arglist2), Base3


(arglist3)… … … BaseN (arglistN)
{
Body of constructor
}

As seen above, the header of derived constructor contains two parts separated by colon(:). The first part
provide declaration of arguments which are passed to derived constructors and second part lists the function
calls to base class constructors.
Basel (arglist1), Base2(arglist2), .. .. .. … BaseN(arglistN) are calls to constructors Basel(),Base2(), … …
… BaseN() and the arglist1, arglist2, .. .. .. arglistN represents the actual parameterthat are passed to the
base constructors. Arglist1, Arglist2 through ArglistN the formal arguments of derived class constructor.
Example 6.9:
//program to demonstrate constructor in inheritance.wballesnat #include<iostream.hupenos siya

(2101
Output:-

Y initialized

8
X initialized

Z initialized evolutaaf

〒40.549999nyms of

c=70) (

In above example, we have created object ob of class Z and passed four values to its constructor. Among
them the first two values are used to initialize the data elements of classes X and Y while last two values
initialize the class Z. While inheriting the classes X and Y, we have used the declaration as, class Z: public
Y, public X. This means the constructor of Y will be first called which is followed by the constructor of X
and lastly the constructor of Z.
Example 6.10:

//program to demonstrate constructor in derived class

#include<iostream.h>

#include<conio.h>

<doinco>sbulani

c2.incount();

count is: 3

c3.decount();

count is: 2

c3.decount();

count is: 3

c3.incount();

count is: 49

getch();return 0;

count is: 48

count is: 49

Costs and Benefits of Inheritance


Benefits
1. It supports the concept of hierarchical classification.
2. The derived class inherits some or all the properties of the base class.

9
3. Inheritance provides the concept of reusability. This means additional features can be added to an
existing class without modifying the original class. This helps to save development time and reduce
cost of maintenance.
4. Code sharing can occur at several places.
5. It will permit the construction of reusable software components. Already several such libraries are
commercially available.
6. The new software system can be generated more quickly and convemently by rapid prototyping.
7. Programmers can divide their work among themselves and later on combine their codes.

Costs
1. The base and derived classes get tightly coupled. This means one cannot be used independent of each
other that is to say they are interconnected to each other.
2. We know that inheritance uses the concept of reusability of program codes so the defects in the
original code module might be transferred to the new module thereby resulting in defective program
modules

10

You might also like