0% found this document useful (0 votes)
10 views15 pages

Unit 6-Inheri C++

This chapter discusses inheritance in object-oriented programming, particularly in C++. It explains the types of inheritance, including single, multilevel, multiple, hierarchical, and hybrid inheritance, as well as the use of constructors and destructors in derived classes. Additionally, it covers visibility modifiers and their impact on member accessibility between base and derived classes.

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 PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views15 pages

Unit 6-Inheri C++

This chapter discusses inheritance in object-oriented programming, particularly in C++. It explains the types of inheritance, including single, multilevel, multiple, hierarchical, and hybrid inheritance, as well as the use of constructors and destructors in derived classes. Additionally, it covers visibility modifiers and their impact on member accessibility between base and derived classes.

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 PDF, TXT or read online on Scribd
You are on page 1/ 15

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 derived classes 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: protected ABC //(protected derivation


{ members of abc };

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


{ };

1
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 they are inaccessible
by the objects of the derived class.
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

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(){ B=10
c=b*get_a(); C=200
}

2
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.

#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(); }
int get_a(); void B:: show(){
}; cout<<"b="<<b<<"\nc="<<c;
class B: private A }
{ int main(){
int c; B x;
public: x.calc();
void calc(); x.show();
void show(); getch();
}; return 0; Output:-
void A:: input_ab() }
{ Enter two number: 20 10
cout<<"Enter values for a and b:"; B=10
cin>>a>>b; C=200
}

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
Protected
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
3
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.
Note: The private members in the base class cannot be directly accessed in the derived class, while
protected members can be directly accessed.

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 inheritance ❌ Private ❌ Not inheritance


Protected
Public

Class D1:public B
Class D2:private B
Private
Private
Protected
Protected
Public
Public

Class X: publicD1, 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.

Fig6.3: Multi-level Inheritance

Example 6.5:
#include<iostream.h> void showmarks() {
#include<conio.h>
class info { cout<<"\nChemistry="<<m1<<"\nEnglish="<< 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 { tot 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.

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.

5
fig 6.4: Multiple Inheritance
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; }
Output:-
void show()
Enter value of x:10
{ cout<<endl<<x<<" "<<y<<" "<<z;
Enter value of z:30
cout<<"\ntotal="<<total;
Enter value of y:20
}
};
10 20 30
int main()
Total:60
{ clrscr();
D k;
k.get_x();
k.get_y();
k.get_z();
k.calc();
k.show();
getch();
return 0;
}

6
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.

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 6.7:
//Program to demonstrate Hierarchical Inheritance
#include<iostream.h> class D: public A {
#include<conio.h> int w;
class A{ public:
protected: int x; void calcw()
public: { w= 4*x; }
void getx(){ void showw()
cout<<”\Enter x:”; { cout<<”\nw=”<<w; }
cin>>x; };
} int main()
}; {
class B:public A{ clrscr();
int y; B b1; C c1 ; D d1;
public: b1.getx(); b1.calcy();
void calcy() b1.getx(); c1.calcz();
{ y=2*x; } d1.getx(); d1.calcw();
void showy() { cout<<”\nAfter Computation: -“;
cout<<”\ny=”<<y; } b1.showy();
}; c1.showz(); Output:-
class C: public A d1.showw(); Enter x:10
{ int z; getch(); Enter x:30
public: return 0; Enter y:20
void calcz() }
{ z=3*x; } After Computation:-
void showz() y=4
{ cout<<”\nz=”<<z; } z=12
}; w=24

7
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.

Figure 6.7: Multilevel, multiple inheritance. Figure 6.8: Hierarchical, multiple inheritance
Example 6.8:
// Program to demonstrate hybrid inheritance
# include<iostream.h> class result:public marks,public spots
#include<conio.h> {
class student float total;
{ public:
protected: int roll; void show(){
public: total=m1+m2+score;
void getroll(int r) showroll();
{ roll = r; } showmarks();
void showroll() showscore();
{ cout<<"Roll no:"<<roll<<endl; } cout<<"Total score=
}; "<<total<<endl;
class marks: public student }
{ protected: float m1,m2; };
public: int main() {
void getmarks(float x, float y) clrscr();
{ m1=x; m2=y; } result stud1;
void showmarks() stud1.getroll(1);
{ cout<<"\nMarks obtained:\n" <<"Subject 1 = stud1.getmarks(70.5,80.0);
"<<m1<<"\nSubject 2 = "<<m2<<endl; } stud1.getscore(10);
}; stud1.show();
class spots { getch();
proteced:float score; return 0;
public: }
void getscore(float s)
{ score =s; }
Output:-
void showscore(){
Roll no:1
cout<<"Spots
weightage="<<score<<endl; } Mark obtained:
}; Subject 1=70.5
Subject 2=80
Spots weightage=10
Total score=160.5

8
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 they appear
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 parameter that are
passed to the base constructors. Arglist1, Arglist2 through ArglistN the formal arguments of derived
class constructor.

9
Example 6.9:
//program to demonstrate constructor in inheritance.
#include<iostream.h> class Z: public Y, public X
#include<conio.h> { int c,d;
class X public:
{ float a; Z(float m, float n, int q, int r): X(m), Y(n)
public: { c=q;
X(float i) d=r;
{ a=I; cout<<”z initalized \n”; }
cout<<”X initialized \n”; void showcd()
} { cout<<”c =”<<c<<endl<<”d=”<<d;
void showa() cout<<endl; }
{ cout<<”a=”<<a<<endl; } };
}; int main(){
class Y clrscr();
{ float b; Z ob(40.55,50.0,70,80);
public: ob.showa(); Output:-
Y(float i) ob.showb(); Y initialized
{ b=i; ob.showcd(); X initialized
cout<<”Y initialized \n”; getch(); Z initialized
} return 0; a=40.54999
void showb() } b=50
{ cout<<”b=”<<b<<endl; } c=70
}; d=80

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> int main()
#include<conio.h> { clrscr();
class counter1 counter2 c2; /* compiler creates object c2 of
{ protected: int count; type counter2 and calls no argumen constructor
public: of counter2*/
counter1()
{ count= 4; } counter2 c3(50); // value 50 is passes to one
counter1(int c) argument constructor of counter2.
{ count=c; } c2.decount();//’This constructor calls
void incount() constructor of class counter1.
{ count++; c2.decount();
cout<<” count is: “<<count<<endl; c2.incount();
} c3.decount();
};
class counter2: public counter1
{ public:
counter2(): counter1(){}

10
counter2(int c): counter1 (c ) {} //counter2 c3.decount();
Output:-
calls countert of base class c3.incount();
// one argument constructor of counter2 calls getch(); count is: 3
one argument constructor of counterl return 0; count is: 2
void decount() } count is: 3
{ count--; count is: 49
vout<<” count is: “<<count<<endl; 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.
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

Function Overriding
Function overriding in C++ is termed as the redefinition of base class function in its derived class
with the same signature i.e. return type and parameters. It falls under the category of Runtime
Polymorphism.
Syntax:
Class Parent{
Access_modifier:
Return_type name_of_the_function(){ // overridden function
//body
}
};
Class child : public Parent {
Access_modifier:
Return_type name_of_the_function(){ // overriding function

11
//body
}
};
Sample example program:
#include <iostream.h>
class Parent {
public: void add() // overridden function
{ cout << “Base Function” << endl; }
};
class Child : public Parent {
public: void add() // overridden function
{ cout << “Derived Function” << endl; }
};
int main(){ Output:
child A;
A.add(); Derived function
return 0; }

Variations in Function Overriding


1.Call Overridden Function From Derived Class
We can call the overridden function from derived class using scope resolution operator.
Syntax:
base_class name :: overridden function

#include <iostream.h>
class Parent {
public:
void fun()
{
cout << “Base Function Exucated” << endl;
}
};

class Child : public Parent {


public:
void fun()
{
cout << “Derived Function” << endl;
parent::fun(); // call of overridden function
}
};
int main() Output:
{ Derived function
child A; Base function executed
A.fun();
return 0;
}

12
2.Call Overridden Function Using Pointer
Use of pointer we can direct call the overridden function of base class.
Syntax:
base_classname *ptr= &derived_classname
ptr ->overridden_function name

#include <iostream>
class test {
public:
int a=5,b=3;
void mult()
{
cout << “Product of a and b is:” <<a*b<< endl;
}
};
class result : public test {
public:
void mult()
{
cout << “HELLO” << endl;
}
};
int main()
{
result ob;
test* ptr = &result; // pointer of test type that points to result
ptr->mult(); // call function of Base class using ptr
return 0;
}

Output:
Product of a and b:15

3.Access of Overridden Function to the Base Class


We can direct call the overridden function of base class using dot(.) and scope resolution (::)
operator.
Syntax: derived_classne.base_classname:: overridden function

#include <iostream.h>
class XYZ {
public:
void display()
{
cout << “Base Function” << endl;
}
};

13
class ABC : public XYZ{
public:
void display ()
{
cout << “Derived Function” << endl;
}
}; Output:
Derived class
int main() Base function
{
ABC ob;;
ob.display();
// access display () function of the Base class
ob.XYZ:: display ();
return 0;
}

// example program to access overridden function


#include <iostream>
class Parent
{
public:
void Print() // defining the overridden function
{
cout << “I am the Parent class function” << endl;
}
};

class Child : public Parent


{
public:
void Print() // defining of the overriding function
{
cout << “I am the Child class function” << endl;
}
};

int main()
{
child ob1, B; // create instances of the derived class
ob1. Print(); // call the overriding function
B.Parent:: Print(); // call the overridden function of the Base class
return 0;
}
Output:
I am the child class function
I am the parent class function

14
Function Overloading Vs Function Overriding
Function Overloading Function Overriding

It falls under Compile-Time polymorphism It falls under Runtime Polymorphism

A function can be overloaded multiple times A function cannot be overridden multiple


as it is resolved at Compile time times as it is resolved at Run time

Can be executed without inheritance Cannot be executed without inheritance

They are in the same scope They are of different scopes.

15

You might also like