C++ Unit-6
C++ Unit-6
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.
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.
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
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
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:
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.
Fixample 7.8:
void
Total score=160.5
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:
#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
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