0% found this document useful (0 votes)
14 views58 pages

Inheritance

The document explains the concept of inheritance in object-oriented programming (OOP), emphasizing its role in reusability and efficiency by allowing new classes to derive properties from existing ones. It details various types of inheritance, including single, multiple, hierarchical, multilevel, and hybrid inheritance, along with their syntax and examples in C++. Additionally, it addresses visibility control of inherited members and ambiguity resolution in cases of multiple inheritance.
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)
14 views58 pages

Inheritance

The document explains the concept of inheritance in object-oriented programming (OOP), emphasizing its role in reusability and efficiency by allowing new classes to derive properties from existing ones. It details various types of inheritance, including single, multiple, hierarchical, multilevel, and hybrid inheritance, along with their syntax and examples in C++. Additionally, it addresses visibility control of inherited members and ambiguity resolution in cases of multiple inheritance.
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/ 58

Inheritance

▣ Reusability is feature of OOP.

▣ We could reuse reuse something that already exists rather than trying to
create the same all over again.

▣ It would not only save time and money but also reduce reliability.

▣ The reuse of a class that has already been tested, debugged and use many
time can save us the effort of developing and testing the same again

▣ Concept of reusability

▣ C++, a new class can reuse the property of existing class

▣ The mechanism of deriving a new class from old class is known as
inheritance.
▣ The mechanism of deriving a new class from
old class is known as inheritance

Base Class ( Old Class)

Derived Class (New class)

▣ Derived class inherits some or all the properties


from base class
▣ A class can also inherit properties from more
than one level
Making private member inheritance
◼ What can be done if the private data needs to be inherited by a
derived class.
◼ This can be achieved by modifying the limit of the private
member by making it public.
◼ C++ provide 3rd visibility made protected
◼ A member declare under protected is accessible by the member
function within its class and any class immediately derived from
it.
◼ It can not be accessed by the function outside these two classes.
◼ When a protected member is inherited in public mode, it become
protected in the derived class and accessible by the member
function of the derived class.
◼ Protected member , inherited in the private mode derivation
become private in the derived class.

Effect of inheritance on the visibility of member
▣ Class alpha
▣ {

▣ private: 🡪 //visible to member function within it class


▣ -----------
▣ ------------
▣ -----------

▣ protected: 🡪 //visible to member functions of its own & derived class


▣ -----------
▣ -----------
▣ -----------

▣ public: 🡪 //visible to all functions in the program


▣ ------------
▣ ------------
▣ ------------
▣ }
Visibility of inherited
member
Base Class
Derived Class Visibility
visibility

Public Private Protected


Derivation Derivation Derivation

Private Not Inherited Not Inherited Not Inherited

Protected Protected Private Protected

public Public Private Protected


All
User
Own member
Public functions and
friendly
functions and
Protected classed

Private
Derive
Class
Member

A simple view of access control to the member of a class


Type of inheritance
▣ a) Single Inheritance

▣ b) Multiple Inheritance

▣ c) Hierarchical Inheritance

▣ d) Multilevel Inheritance

▣ e) Hybrid Inheritance
How to define Derived class
Syntax:
🡪Class derived_class _name: visibility_mode base _class_name
{
◼ ------------- //member of derived class
◼ -------------
◼ -------------
};
Example:
▣ 🡪Class ABC : private YXZ //[Private derivation]
{
Member of ABC
---------------------
};

▣ 🡪Class ABC : public YXZ //[Public derivation]


{
Member of ABC
--------------------
};

▣ 🡪Class ABC : YXZ //[Private derivation by default]


{
Member of ABC
-----------------------
};
◼ When a base class is privately inherited by a derived
class , ‘public member ’ of the base class become
‘private member ‘ & The public member of the base
class can only be access by the member function of
the derived class .
◼ Public member of a class can be accessed by its own
objects using dot operator and public member of
base class become public member of derived class in
public inheritance
◼ No member of the base class is accessible to the
object of the derived class.
◼ Private member are not inherited and private
member of a base class will never become the
member of its derived class
Single Inheritance
▣ a) Single Inheritance
B (Base Class)

D (derive class)

Example : Illustrate program shows a Base class B and


derived Class D
The class B contains one private data member, one
public data member and three public member function
The Class D contains one private data member and two
public member function.
▣ // Program for Single Inheritance
▣ #include <iostream>
▣ using namespace std;
▣ class B
▣ {
▣ int a;
▣ public:
▣ int b;
▣ void get_ab();
▣ int get_a(void);
▣ void show_a(void);
▣ };
▣ class D : public B
▣ {
▣ int c;
▣ public:
▣ void mul(void);
▣ void display(void);
▣ };
▣ //============================
▣ void B :: get_ab(void)
▣ {
▣ a=5;
▣ b=10;
▣ }
▣ int B :: get_a()
▣ {
▣ return a;
▣ }
▣ void B :: show_a()
▣ {
▣ cout<<"a= "<<a<<"\n";
▣ }
▣ void D :: mul()
▣ {
▣ c=b*get_a();
▣ }
▣ void D :: display()
▣ {
▣ cout<<"a= "<<get_a()<<"\n";
▣ cout<<"b= "<<b<<"\n";
▣ cout<<"c= "<<c<<"\n\n";
▣ }
▣ //====================================

▣ int main()
▣ {
▣ D d;

▣ d.get_ab();
▣ d.mul();
▣ d.show_a();
▣ d.display();

▣ d.b=20;
▣ d.mul();
▣ d.display();

▣ return 0;
▣ }
Multilevel Inheritance
A🡪 Base Class( Grandfather)

B🡪 Intermediate Base
Class(father)

B 🡪 Derived(child)
▣ A derive class with multilevel inheritance is
declared as follows
▣ Class A {……..}
▣ Class B: public A {……..}
▣ Class C: public B {……..}
▣ This process can be extended to any number of
level
▣ Assume that the test results of a batch of students
are stored in three different classes.
▣ Class student stores the roll-number , class test
stores the marks obtained in two subjects and class
result contains the total marks obtained in the test.
▣ The class result can inherit can the details of the
marks obtained in the test and the roll-number of
students through multilevel inheritance.
▣ #include <iostream>
▣ using namespace std;
▣ class student
▣ {
▣ protected:
▣ int roll_number;
▣ public:
▣ void get_number(int);
▣ void put_number(void);
▣ };

▣ void student :: get_number(int a)


▣ {
▣ roll_number=a;
▣ }
▣ void student :: put_number()
▣ {
▣ cout<<"Roll number: "<< roll_number<<"\n";
▣ }
▣ class test : public student //first level derivation
▣ {
▣ protected:
▣ float sub1;
▣ float sub2;
▣ public:
▣ void get_marks(float,float);
▣ void put_marks(void);
▣ };

▣ void test :: get_marks(float x , float y)


▣ {
▣ sub1=x;
▣ sub2=y;
▣ }
▣ void test :: put_marks()
▣ {
▣ cout<<"Marks in sub1="<<sub1<<"\n";
▣ cout<<"Marks in sub2="<<sub2<<"\n";
▣ }
▣ class result : public test // Second level derivation
▣ {
▣ float total; // private by default
▣ public:
▣ void display(void);
▣ };
▣ void result :: display(void)
▣ {
▣ total=sub1+sub2;
▣ put_number();
▣ put_marks();
▣ cout<<"Total="<<total<<"\n";
▣ }
▣ int main()
▣ {
▣ result student1;

▣ student1.get_number(111);
▣ student1.get_marks(75.0,59.5);

▣ student1.display();

▣ return 0;
▣ }
▣ Output:
▣ Roll number: 111
▣ Marks in sub1=75
▣ Marks in sub2=59.5
▣ Total=134.5
Multiple Inheritance

A B C n number of base class

D
one Derive class
A class can inherit the attribute of two or more classes
as shown in fig. this is known multiple inheritance
▣ Multiple inheritance allow us to combine the
features of several existing classes as a starting
point for defining new classes.
▣ It’s like a child inheriting the physical features
of one parent and the intelligence of another
▣ Syntax of derived class with multiple base class
Class D : visibility B1 , visibility B2….
{
-------------visibility may be either public or private
-------------
-------------
} ;
Program for Multiple
inheritance
▣ // Program for Multiple Inhritance
▣ #include <iostream>

▣ using namespace std;

▣ class M
▣ {
▣ protected:
▣ int m;
▣ public:
▣ void get_m(int);
▣ };
▣ class N
▣ {
▣ protected:
▣ int n;
▣ public:
▣ void get_n(int);
▣ };

▣ class P: public M, public N


▣ {
▣ public:
▣ void display(void);
▣ };
▣ void M :: get_m(int x)
▣ {
▣ m=x;
▣ }
▣ void N :: get_n(int y)
▣ {
▣ n=y;
▣ }
▣ void P ::display(void)
▣ {
▣ cout<<"m="<<m<<"\n";
▣ cout<<"n="<<n<<"\n";
▣ cout<<"m*n="<<m*n<<"\n";
▣ }

▣ int main()
▣ {
▣ P p;
▣ p.get_m(10);
▣ p.get_n(20);
▣ p.display();
▣ cout<<"Hello World";

▣ return 0;
▣ }
Hierarchical Inheritance
▣ We have discussed so for how inheritance can be used
to modify a class when it did not satisfy the
requirements of a particular problem on hand.

▣ Additional member are added through inheritance to


extend the capabilities of a class.

▣ Another interesting application of inheritance is to use


it as a support to the hierarchical design of a program.

▣ Many programming problems can be cast into a


hierarchical design of a problem.
Hierarchical classification of
students

Student

Engineering Medical

Mechanical Computer MBBS


▣ Fig shows a hierarchical classification of
students in a university
▣ All the students have certain things in common
▣ In C ++ , such problem can be easily converted
into class hierarchies
▣ The base class will include all the features that
are common to the subclasses
▣ A subclasses can be constructed by inheriting
the properties of the base
▣ A sub class can serve as a base class for the
lower level classes and so on
Hybrid Inheritance
▣ There could be situation where we need to apply
two or more type of inheritance to design a
program.

▣ For instance , consider the case of processing the


student results discussed multilevel inheritance .

▣ Assume that we have to give weightage for sports


before finalizing the result.

▣ The weightage for sports is stored in a separate


class called sports.
Hybrid Inheritance
◼ The new inheritance relationship between the
various classes would be as shown in fig
Student

Sport
Test

Result
Program for Hybrid Inheritance
▣ #include <iostream>

▣ using namespace std;

▣ class student
▣ {
▣ protected:
▣ int roll_number;
▣ public:
▣ void get_number(int a)
▣ {
▣ roll_number=a;
▣ }
▣ void put_number(void)
▣ {
▣ cout<<"Roll Number:"<<roll_number<<"\n";
▣ }
▣ };
▣ class test: public student
▣ {
▣ protected:
▣ float part1, part2;
▣ public:
▣ void get_marks(float x , float y)
▣ {
▣ part1=x;
▣ part2=y;
▣ }
▣ void put_marks(void)
▣ {
▣ cout<<" Marks obtain:"<<"\n"
▣ <<"part1="<<part1<<"\n"
▣ <<"part2="<<part2<<"\n";
▣ }
▣ };
▣ class sport
▣ {
▣ protected:
▣ float score;
▣ public:
▣ void get_score(float s)
▣ {
▣ score=s;
▣ }
▣ void put_score(void)
▣ {
▣ cout<<"Sport wt:"<<score<<"\n\n";
▣ }
▣ };
▣ class result: public test , public sport
▣ {

▣ float total;
▣ public:
▣ void display(void);
▣ };
▣ void result :: display(void)
▣ {
▣ total=part1+part2+score;

▣ put_number();
▣ put_marks();
▣ put_score();
▣ cout<<"Total score: "<<total<<"\n";
▣ }
▣ int main()
▣ {
▣ result student_1;
▣ student_1.get_number(1234);
▣ student_1.get_marks(27.5,33.0);
▣ student_1.get_score(6.0);
▣ student_1.display();

▣ return 0;
▣ }
Ambiguity Resolution in Inheritance

▣ Occasional , we may face a problem using the


multiple inheritance , when a function with the
same name appears in more than one base class
▣ Consider the following two classes
▣ Same function name in multiple classes
=ambiguity scope resolution operation is
ambiguity resolution
Example : Ambiguity
Resolution
▣ Class M
▣ {
▣ public :
▣ void display( void )
▣ {
▣ cout<<“class M\n”;
▣ }
▣ };
▣ Class N
▣ {
▣ public
▣ void display( void)
▣ {
▣ cout<<“class N \n”;
▣ }
▣ };
▣ Which display( ) function is used by the
derived class when we inherit these two classes
▣ We can solve this problem by define a named
instance within the derived class , using the
class resolution operator with the function
Class P : public M , N
{
public:
void display( void) //overrides display( ) of M &N
{
M : : display( );
}
};
Ambiguity may also arise in single inheritance
application .
Class A
{
public :
void display( )
{
cout<<“A \n”;
}
};
▣ Class B : public A
▣ {
▣ public :
▣ void display ( )
▣ {
▣ cout<<“B \n”;
▣ }
▣ };
▣ In this case , the function in the derived class
overrides the inherited function and
▣ - a simple call to display ( ) by B only.
▣ However , we may invoke the function define in A
by using the scope resolution operator to specify
the class
▣ Int main ( )
▣ {
▣ Bb; // derived class object
▣ b.display( ); // invoked dispay( ) in B
▣ b.A :: display ( ); //……………..in A
▣ b.B :: display( ); // ………………in B
▣ return 0;
▣ }
▣ This will produce the following output
▣ Output: B
▣ A
▣ B
Virtual Base class
▣ We have just discussed a situation which
would require the use of both the multiple and
multilevel inheritance.

▣ Consider a situation where all the three kind of


inheritance namely multiple , multilevel and
hierarchical inheritance are involved.
▣ This is illustrated in fig

GrandParent

Parent1 Parent2

child
▣ The child has two direct base classes ‘ Parent1’ and ‘parent2’ which
themselves have a common base class ‘Grandparent’.

▣ The ‘child’ inherits the traits of ‘Grandparent’ via two separate


path.

▣ It can also inherit directly as shown by the broken line


▣ The ‘ Grandparent ‘ is some time referred to as indirect base class.

▣ Inheritance by the ‘child’ as in fig might pose some problem . All


the public and protected members of ‘Grandparent’ are inherited
into ‘child’ twice. First via ‘parent1’ and ‘parent2’.

▣ This means , ‘child’ would have duplicate set of the members


inherited from ‘Grandparent’.

▣ The introduces ambiguity and should be avoided

▣ The duplication of inherited members due to these multiple path


can avoided by making the common base class
▣ As virtual base class while declaring the direct or intermediate base class
▣ Class A // Grandparent
▣ {
▣ ……….
▣ ……….
▣ }
▣ Class B1: virtual public A //parent1
▣ {
▣ ……….
▣ ……….
▣ }
▣ Class B2 : public virtual A // parent2
▣ {
▣ …………
▣ ………….
▣ }
▣ Class C : public B1 , public B2 // child
▣ {
▣ ………... //only one copy of A will be inherited
▣ ………..
▣ }
▣ When a class is made a virtual base class , C++ take necessary care to see
that only one copy of that class is inherited , regardless of how many
inheritance path exist between the virtual base class and a derived class.

▣ The keyword virtual and public may be used in either order.


▣ Example : consider again the student - result processing system discussed
▣ Assume that the class sports derives the roll_number from the class
student.

student

test sport

result
Program to implement the concept of virtual
base class
▣ #include <iostream>

▣ using namespace std;

▣ class student
▣ {
▣ protected:
▣ int roll_number;
▣ public:
▣ void get_number(int a)
▣ {
▣ roll_number=a;
▣ }
▣ void put_number(void)
▣ {
▣ cout<<"Roll Number:"<<roll_number<<"\n";
▣ }
▣ };
▣ class test: virtual public student
▣ {
▣ protected:
▣ float part1, part2;
▣ public:
▣ void get_marks(float x , float y)
▣ {
▣ part1=x;
▣ part2=y;
▣ }
▣ void put_marks(void)
▣ {
▣ cout<<" Marks obtain:"<<"\n"
▣ <<"part1="<<part1<<"\n"
▣ <<"part2="<<part2<<"\n";
▣ }
▣ };
▣ class sport: public virtual student
▣ {
▣ protected:
▣ float score;
▣ public:
▣ void get_score(float s)
▣ {
▣ score=s;
▣ }
▣ void put_score(void)
▣ {
▣ cout<<"Sport wt:"<<score<<"\n\n";
▣ }
▣ };
▣ class result: public test , public sport
▣ {

▣ float total;
▣ public:
▣ void display(void);
▣ };
▣ void result :: display(void)
▣ {
▣ total=part1+part2+score;

▣ put_number();
▣ put_marks();
▣ put_score();
▣ cout<<"Total score: "<<total<<"\n";
▣ }
▣ int main()
▣ {
▣ result student_1;
▣ student_1.get_number(1234);
▣ student_1.get_marks(27.5,33.0);
▣ student_1.get_score(6.0);
▣ student_1.display();

▣ return 0;
▣ }
Constructor in derive class
▣ If base class constructor does not have any argument the derived class need
not have a constructor function.

▣ If base class contains one or more arguments then it is mandatory for the
derived class to have a constructor and pass the arguments to the base
constructor.

▣ In inheritance we create object of any derived class , so it makes scenes for


the derived class to pass arguments to the base class constructor.

▣ When both the base and derived class contains constructors the base
constructor is executed first and then the constructor in the derived class is
executed

▣ In multiple inheritance , the base classes are constructor in the order in


which they appear in the declaration of the derived class

▣ The constructor of the derived class receives the entire list of value as its
arguments and passes them on to the base constructors in order they are
declared in derive
Program for constructor in derived
class
▣ #include <iostream>

▣ using namespace std;

▣ class alpha
▣ {
▣ int x;
▣ public:
▣ alpha(int i)
▣ {
▣ x=i;
▣ cout<<"alpha initialized \n";

▣ }
▣ void show_x(void)
▣ {
▣ cout<<"x="<<x<<"\n";
▣ }
▣ };
▣ class beta
▣ {
▣ float y;
▣ public:
▣ beta(float j)
▣ {
▣ y=j;
▣ cout<<"beta initialized\n";
▣ }
▣ void show_y(void)
▣ {
▣ cout<<"y="<<y<<"\n";
▣ }
▣ };
▣ class gamma: public beta ,public alpha
▣ {
▣ int m,n;
▣ public:
▣ gamma(int a,float b,int c,int d):
▣ alpha(a) , beta(b)
▣ {
▣ m=c;
▣ n=d;
▣ cout<<"gamma initialized\n";
▣ }
▣ void show_mn(void)
▣ {
▣ cout<<"m="<<m<<"\n"
▣ <<"n="<<n<<"\n";
▣ }
▣ };
▣ int main()
▣ {
▣ gamma g(5,10.75,20,30);
▣ cout<<"\n";
▣ g.show_x();
▣ g.show_y();
▣ g.show_mn();
▣ cout<<"Hello World";

▣ return 0;
▣ }

You might also like