0% found this document useful (0 votes)
25 views

Inheritance

inheritance

Uploaded by

bug myweeks
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Inheritance

inheritance

Uploaded by

bug myweeks
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 57

Inheritance

lect#22
Introduction

 Reusability--building new components by utilizing existing components-


is yet another important aspect of OO paradigm.
 It is always good/ “productive” if we are able to reuse something that is
already exists rather than creating the same all over again.
 This is achieve by creating new classes, reusing the properties of
existing classes.
It saves money , time, efforts etc.
Definition
• This mechanism of deriving a new class from existing/old
class is called “inheritance”.
• The old class is known as “base” class, “super” class or
“parent” class.
• The new class is known as “sub” class, “derived” class, or
“child” class.
• Example:

M AM M ALS

DO G S C ATS H U M AN S

L IO N S T IG E R S LEO PAR DS
Types of Inheritance

1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance
Defining Derived classes

• Syntax:
class DerivedClassName : access-level BaseClassName
where
– access-level specifies the type of derivation
• private by default, or
• Public
• Protected

• Any class can serve as a base class


– Thus a derived class can also be a base class
Implementing Inheritance in C++ by Deriving Classes From the Base Class
• Syntax:
class base_classname
{

};
class derived_classname : <access-specifier>base_classname
{
...
};
Examples
Class ABC : private XYZ //private derivation
{
Members of ABC
};

Class ABC : public XYZ //public derivation


{
Members of ABC
};

Class ABC : XYZ //private derivation by default


{
Members of ABC
};
Public inheritance

• When a base class is publicly inherited, ‘public


members’ of the base class become ‘public
members’ of the derived class and therefore they
are accessible to the objects of the derived class.
• Note: private members of the base class are not
accessible in the derived class (to preserve
encapsulation)
example
Class base_class Class derived_class:public base_class
{ {
Private:
Private: Int num2;
Public:
Int num1; Void derived_read()
Public: {
Cout<<“enter no”;
Void base_read() Cin>>num2;
}
{ Void derived_show()
Cout<<enter a no”; {
Cout<<“no is”<<num2;
Cin>>num1; }
};
} main()
{
Void base_show()
derived_class d1;
{ d1.base_read();
Cout<<“number is”<<num1; d1.derived_read();
d1.base_show();
}
d1.derived_show();
}; getch();
}
Class derived_class:public base_class
{
Private:
Int num2;
Public:
Void derived_read()
{
Cout<<“enter no”;
Cin>>num2;
}
Void derived_show()
{
Cout<<“no is”<<num2;
}
};
void main()
{
derived_class d1;
d1.base_read();
d1.derived_read();
d1.base_show();
d1.derived_show();
getch();
}
Single Inheritance
#include<iostream.h> class D:public B //public
derivation
class B {
{ int a; //private not inheritable
int c;
public: //ready for inheritance
public:
int b;
void mul(void)
void get_ab()
{c= b*get_a(); }
{a=5; b=10;}
void display()
int get_a()
{ return a; } {cout<<“a=“<<get_a()<<“\n”;
cout<<“b=“<<b<<“\n”;
void show_a() cout<<“c=“<<c<<“\n”;
{cout<<“a=“<<a<<“\n”; } }
};
};
int main()
{
D d;
d.get_ab();
d.mul();
d.show_a();
d.display();

d.b=20;
d.mul();
d.display();
return 0;
}
Private inheritance

• Public members of base class become private


members of derived class
• Protected members of base class become private
members of derived class
• Public and protected members are only available to
derived-class member functions - not to a derived
object.
• They are inaccessible to the objects of the derived
class.
Single Inheritance
#include<iostream.h> class D:private B //private
derivation
class B
{ int c;
{ int a; //private not inheritable
public:
public: //ready for inheritance
void mul(void)
int b;
{ get_ab();
void get_ab()
c= b*get_a(); }
{a=5; b=10;} void display()
int get_a() { show_a();
{ return a; } cout<<“b=“<<b<<“\n”;
void show_a() cout<<“c=“<<c<<“\n”;

{cout<<“a=“<<a<<“\n”; } }
};
};
int main()
{
D d;
//d.get_ab(); //won’t work
d.mul();
//d.show_a(); //won’t work
d.display();

//d.b=20; //won’t work


d.mul();
d.display();
return 0;
}
Protected inheritance

• A member declared as protected is accessible by


the member functions within its class and any class
immediately derived from it.
• It cannot be accessed by the functions outside
these two classes.
• It is possible to inherit a base class in protected
mode. In this, Public and protected members of the
base class become protected members of the
derived class.
Private: // visible to member function within class//

Protected: // visible to member functions of its own


and immediate derived class//

Public: // visible to all functions in the program//


#include<iostream>

using namespace std;

#include<conio.h>

class a

protected:

int x;

public:

void getdata(int m)

x=m;

void putdata()

{ cout<<x<<"\t";

};
class b:protected a
{ protected:
int y;
public:
void getdata(int n)
{ y=n;
a::getdata(5);
} void putdata()
{ cout<<y<<"\t";
a::putdata(); }
void sum()
{
int z=x+y;
cout<<z<<"\t"; } };
void sum()
{
int z=x+y;
cout<<z<<"\t";

}
};

int main()
{
b b1;

b1.getdata(8);
b1.putdata();
b1.sum();

getch();
}
Class B
Private Not Inheritable
Protected

Public

Class D1:public B ClassD2:private B

Private Private

Protected Protected

Public Public

Class X:public D1,protected D2

Private

Protected

Public
Access Rights of Derived Classes
Type of Inheritance

Private Protected Public


for Members
Access Control

inheritance inheritance inheritance


private Not inherited Not inherited Not inherited
protected Private protected protected
public private protected public
• The type of inheritance defines the access level for the
members of derived class that are inherited from the base
class
Adding members “Publicly & Privately”

Public Inheritance Private Inheritance


Multiple Inheritance
• Is the phenomenon where a class may inherit
from two or more classes
• Syntax:
class derived : public base1, public base2
{
//Body of class
}; A B

• Base classes are separated by comma


C
Multiple Inheritance
#include <iostream.h> void P::display(void)
class M {
{ cout<<“m=“<<m<<“\n”;
protected: cout<<“n=“<<n<<“\n”;
int m; cout<<“m*n=”<<m*n<<“\n”;
public:
void get_m(int x) }
{ m=x; } int main()
};
{
class N
{ P p;
protected:
int n; p.get_m(10); //m=10
public:
void get_n(int y) p.get_n(20); //n=20
{ n= y;}
}; p.display(); //m*n = 200
class P:public M, public N
return 0;
{ public:
void display(void); }
};
Ambiguities in Multiple Inheritance (Contd.)
• Can be resolved in two ways:
– By using the scope resolution operator
• D1.base1::disp();
• D1.base2::disp();
OR
Defining explicitly member function
– By overriding the function in the derived class
Void disp()
{
base1::disp();
base2::disp();
}
Multilevel Inheritance
• It is also possible to derive a class from an existing
derived class.
• It is implemented by defining atleast three classes.
• Each derived class must have a kind of relationship
with its immediate base class.
A

C
Multilevel Inheritance
class result:public test
#include <iostream.h>
class student
{ { float total ;
protected: public:
int roll_no;
public: void display() ;
void get_no(int a) };
{ roll_no=a; }
void put_no() void result:: display()
{ cout<<roll_no; {
} total= sub1+sub2;
};
put_no(); //function of
class test : public student
{ class student
protected: put_marks();
float sub1,sub2; //function of class test
public: cout<<“total = “<<total;
void get_marks(float x, float y) }
{ sub1=x; sub2=y; }
void put_marks(void) int main()
{ cout<<“Marks in sub1”<<sub1; {
cout<<“Marks in sub2”<<sub2; result student1;
} student1.get_no(102);
}; student1.get_marks(80.0,98.5);
student1.display();
void result:: display()
{
total= sub1+sub2;
put_no(); //function of class student
put_marks(); //function of class test
cout<<“total = “<<total;
}
int main()
{
result student1;
student1.get_no(102);
student1.get_marks(80.0,98.5);
student1.display();
return 0;
}
Overriding and Overloading
Parent Class Functions
• When any class member function is called, the
following steps take place:
1. The compiler looks for a matching function in the class of
the object using the function name
2. If no match is found in this class, the compiler looks for a
matching function in the parent class
3. If no match is found in the parent class, the compiler
continues up the inheritance hierarchy, looking at the
parent of the parent, until the base class is reached
4. If no match is found in any class, an error message is issued

34
Ambiguity in Multiple Inheritance
• Can arise when two base classes contain a function of the
same name
Example:
#include<iostream>
class base1
{
public:
void disp()
{
cout << "Base1" <<endl;
}
};
class base2
{
int main()
public:
{
void disp() derived Dvar;
{ //Ambiguous function call
cout<< "Base2"<<endl; Dvar.disp();
return 0;
} }
};
class derived : public base1,public
base2
{
//Empty class
};
• Can be resolved
– By overriding the function in the derived class
Void disp()
{
base1::disp();
base2::disp();
}
• Ambiguity in Single Inheritance

class A
{ int main()
public:
{
void display()
{ B b;
cout<<“A\n”; b.display(); // invokes
} display() in B
}; return 0;
class B: public A }
{ In this case, the function in
public: the derived class overrides
void display() the inherited function.
{
cout<<“B\n”;
}
};
Can be resolved:
– By using the scope resolution operator
int main()
{
B b;
b.A::display();
b.B::display();
}
Hybrid Inheritance

Record

Marks Avg

Result
Virtual base class
Student

Test score

result

//Multiple copies of the variables of


student class are generated
Virtual base class
class A
{…….
A ………
};
B1 B2 class B1:virtual public A
{…….
…….
C };
class B2:public virtual A
{…….
……..
};
class C:public B1,public B2
{………
………
}; //only one copy of A
will be inherited
Virtual base class
class student class test : virtual public
{ student
protected: int roll_no; {
public: protected: float part1,part2;
void get_no(int a) public:
{ roll_no=a; void get_marks(float x, float y)
} { part1=x; part2=y;}
void put_no(void)
{ cout<<“roll no. :” << roll_no; void put_marks()
} { cout<<“marks
}; obtained”<<“part1”<<part1<<“
part2”<<part2; }

};
class sports: public virtual void result::display(void)
student {
{ protected : total= part1+part2+score;
float score; put_no();
public: put_marks();
void get_score(float s) put_score();
{ score=s; } cout<<“total score: “<<total;
void put_score() }
{ cout<<“sports wt:”<<score; int main()
} }; {
class result : public test , public result student1;
sports student1.get_no(100);
{ float total; student1.get_marks(50.5,65.2);
public: student1.get_score(10.5);
void display(void); student1.display();
}; return 0;
}
Abstract Class
• An abstract class is one that is not used to create
objects.
• An abstract class is designed only to act as a base
class i.e. to be inherited by other classes.
• It is a design concept in program development and
provides a base upon which other classes may be
built.
Constructors and Inheritance

• If a base class constructor takes no arguments, the derived


class need not to have constructor function.
• If any base class contain constructor with one or more
arguments, then it is mandatory for the derived class to have
a constructor and pass the arguments to the base class
constructor.
• When both the derived and base classes contain constructor,
the base class constructor is executed first and then the
constructor in the derived class is executed.
Order of Constructors and destructors in
derived classes
• Derived-class constructor
– Calls the constructor for its base class first to initialize its base-
class members
– If the derived-class constructor is omitted, its default constructor
calls the base-class’ default constructor
• Destructors are called in the reverse order of
constructor calls.
– Derived-class destructor is called before its base-class destructor
Constructors in Derived Class
• The general form of defining a derived constructor is :
Der_constructor(par_list) : base1(par_list1), base2(par_list2)
{
// implementation of derived class constructor
}
Here Der_constructor is the name of derived class constructor
and par_list specifies the list of parameters that the derived
class constructor will receive, out of which some may be used
to initialize its own data members whereas remaining ones may
be passed to its base class constructors.
Initialization list starts with colon(:) and consists of calls to base
class constructors where each call is separated by comma.
Example

• Derived class object created as:

• Definition of constructor called:


Order of Constructors in derived classes
Class B:public A
{ //A() base constructor
}; //B() derived constructor

Class A:public B, public C


{ //B() base first
}; //C() base second
//A() derived

Class A:public B, virtual C


{ //C() virtual base
}; //B() ordinary base
//A() derived
Constructors in derived classes
#include <iostream> class gamma:public beta, public alpha
class alpha {
{ int m,n;
int x; public:
public: alpha(int i) gamma(int a,float b,int c, int d)
{ x=i; :alpha(a), beta(b)
cout<<“alpha initialized” {
void show_x() m=c;
{ cout<<“x=“<<x;} n=d;
}; cout<<“gamma initialized”;
class beta }
{ float y; void show_mn(void)
public: beta(float j) {
{ y=j; cout<<“m=“<<m;
cout<<“beta initialized”;} cout<<“n=“<<n;
void show_y() }
{ };
Cout<<“y=“<<y; }
};
Constructors in derived classes
int main()
{
gamma g(5,12.34,50,20); Output:
g.show_x(); beta initialized
g.show_y(); alpha initialized
g.show_mn(); gamma initialized
return 0;
} x=5
y=12.34
m=50
n=20
Initialization list

• C++ supports another method of initializing the class


objects.
• This method uses what is known as initialization list in
the constructor function
Constructor(par_list) : initialization section
{
// body of constructor
}
• The part immediately following the colon is called
initialization section.
• We use this section to provide initial values to the
base constructors and also to initialize its own class
members
• The initialization section basically contains a list of
initializations separated by commas, known as
initialization list.
Example
Class XYZ
{
int a;
int b ;
Public :
XYZ(int I, int j) : a(i), b(2*j) { }
};
int main()
{ XYZ x(2,3);
getch() return 0; }
//This program will initialize a to 2 and b to 6
Example
class alpha void show_beta(void)
{ {
int x; cout<<“=p”<<p;
public: cout<<“q=“<<q;
alpha (int i) }};
{ class gamma : public beta, public alpha
x=i; {
cout<<“alpha constructed”; int u,v;
} public:
void show_alpha(void) gamma (int a, int b, float c): alpha (a*2),
{ beta(c,c), u(a)
cout<<“x=“<<x; {
} }; v=b;
class beta cout<<“gamma constructed”;
{ }
float p,q; void show_gamma(void)
public: {
beta ( float a, float b) : p(a), q(b+p) cout<<“u=“<<u;
{ cout<<“v=“<<v;
cout<<“ beta constructed”; }
main()
{
gamma g(2,4,2.5);
cout<<“ display number:”;
g. show_alpha();
g. show_beta();
g.show_gamma();
}

OUTPUT:
Beta constructed
Alpha constructed
Gamma constructed
Display Numbers:
x=4
p=2.5
q=5
u=2
v=4

You might also like