Upload
garry-manocha
View
84
Download
3
Embed Size (px)
DESCRIPTION
Inheritance in C++
Citation preview
Another Way to Define A Class: Inheritance
Inheritance Concept
Rectangle Triangle
Polygon
class Polygon{
private: int width, length;public: void set(int w, int
l);}
class Rectangle{private: int width, length;public: void set(int w, int
l); int area();
}class Triangle{
private: int width, length;public: void set(int w, int
l); int area();
}
Inheritance Concept
Rectangle Triangle
Polygonclass Polygon{
protected: int width, length;public: void set(int w, int l);
}
class Rectangle : public Polygon
{public: int area();
}
class Rectangle{protected: int width, length;public: void set(int w, int l); int area();
}
Inheritance Concept
Rectangle Triangle
Polygonclass Polygon{
protected: int width, length;public: void set(int w, int l);
}
class Triangle : public Polygon
{public: int area();
}
class Triangle{protected: int width, length;public: void set(int w, int l); int area();
}
Why Inheritance? Reusability--building new components by
utilising 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.
Save time & money
Cond.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”; and the new class is known as “sub” class, “derived” class, or “child” class.
Parent
Child
Inherited Capability
Inheritance Concepts
Inheritance creates a hierarchy of related class es (types) which share code and interface.
This is also called a “is a” relationship:
A dog is an animal
A teacher is a person
A car is a vehicle
Inheritance Examples
Base Class Derived Classes
Student CommuterStudentResidentStudent
Shape CircleTriangleRectangle
Loan CarLoanHomeImprovementLoanMortgageLoan
Shape class hierarchy
TwoDimensionalShape
Shape
ThreeDimensionalShape
Circle Square Triangle Sphere Cube Tetrahedron
What to inherit?
In principle, every member of a base class (data + member function) is inherited by a derived class just with different access permission
However, there are exceptions forbase class's constructor and destructor base class's friends
Since all these functions are class-specific
What a derived class can add?
New data membersNew member functions (also overwrite existing
ones)
New constructors and destructorNew friends
GenerializationIn UML, inheritance is called generalization
Parent class is more general form of the child class
Or
Child is more specific version of the parent
Defining Derived Classes
Defined by specifying the relationship with the base class in addition to its own details.
Class derived-class : visibility mode base-class
{………….…………. //members of derived class};
Accessing Base Class MembersMember of base class used by derived class
object called as accessibility.
Protected: is accessible by the member functions within its class and any class immediately derived from it.
Inheritance & AccessibilityAccess Specifier
Accessible from own class
From derived class
Form objects outside class
public yes yes yes
protected Yes yes no
private yes no no
Overriding member functions
To override a base-class member function In derived class, supply new version of that function
Same function name, different definitionThe scope-resolution operator may be used to
access the base class version from the derived class
Access Control Over the Members
Two levels of access control over class membersclass definitionVisibility mode
base c lass / supe rc lass /pa ren t c lass
deriv ed c lass / subc lass /ch ild c lass
deriv
e fro
m
mem
bers
goe
s to class Point{
protected: int x, y;public: void set(int a, int b);
}
class Circle : public Point{… …
}
Visibility modePrivate (default)PublicExamples:
This is an example of Single inheritance.
Class A: public X{//members of A};
Class A : private X{ //members of A};
Public Inheritance
class A : public B{ // Class A now inherits the members of Class B
// with no change in the “access specifier” for} // the inherited members
public base class (B)
public members
protected members
private members
derived class (A)
public
protected
not inherited
Private Inheritanceclass A : private B{ // Class A now inherits the members of Class B
// with public and protected members} // “promoted” to private
private base class (B)
public members
protected members
private members
derived class (A)
private
private
not inherited
Protected visibilityWhen a protected member is inherited in
public mode, it becomes protected in derived class. It is ready for further inheritance
A Protected member, inherited in private mode, it becomes private in the derived class. But not further inherited.
Protected Inheritance
class A : protected B{ // Class A now inherits the members of Class B
// with public members “promoted” to protected} // but no other changes to the inherited members
protected base class (B)
public members
protected members
private members
derived class (A)
protected
protected
not inherited
Visibility of inherited members
private protected public
private Not inher. Not inher. Not inher.
protected private Protected protected
public private protected public
Derived Class Visibility
#include <iostream.h>
class B
{ int a;
public:
int b;
void get_ab();
int get_a();
void show_a();
};
class D: public B
{ int c;
public:
void mul();
void display();
};
void B::get_ab()
{ a=5; b=10; }
int B::get_a()
{ return a;
}
void B::show_a()
{ cout<<"a="<<a<<endl; }
void D::mul()
{ c=b*get_a();
}
void D:: display()
{
cout <<"a="<<get_a()<<endl;
cout<<"b="<<b<<endl;
cout<<"c="<<c<<endl;
}
void main()
{ D d;
d.get_ab();
d. mul();
d.show_a();
d.display();
d.b =20;
d.mul();
d.display(); }
Output
a=5
a=5
b=10
c=50
a=5
b=20
c=100
Forms of Inheritance:
The different forms of inheritance are:
Single inheritance (only one super class)Multiple inheritance (several super classes)Hierarchical inheritance (one super class,
many sub classes)Multi-Level inheritance (derived from a
derived class)Hybrid inheritance (more than two types)
A
B
(a) Single Inheritance
C
(b) Multiple Inheritance
A B
(c) Hierarchical Inheritance
B
A
C D
A
C
B
(e) Hybrid Inheritance
B
D
c
A
(f) Multipath Inheritance
B
A
D
c
(d) Multilevel Inheritance
Multilevel Inheritance
A
C
B
Class A{…………..};Class B: public A{……….………};Class C : public B{……..……..};
Class B-----intermediate class
Chain ABC is known as inheritance path
Process can be extended to any number of levels.
Multiple Inheritance
A class can inherit the attributes of two or more classes.
Class D: public A, public B{------………}
A C
D
B
Combines the features of several existing classes to define a new class.
Child inheriting the smartness from his mother & intelligence from father..
Ambiguity Resolution in inheritanceWhen a function with the same name
appears in more than one base class.We can solve this problem by defining a
named instance within the derived class, using the scope resolution operator with the function…
Ambiguity in single inheritance applications
Class A{Public:Void display(){Cout<<“A”;}};
Class B:public A{Public:Void display(){Cout<<“B”;}};
Void main(){B b;b.display();b.A::display();}
Hierarchical Inheritance
A
C DB
Class A{………..};Class B:public A{…..…..};Class C:public A{…….……};
Hybrid Inheritance There could be situations where we need to apply
two or more types of inheritance to design a program. For example
test
Result
Sports
Student
MultilevelMultiple
Virtual Base ClassesThe duplication of inherited members due to
multiple paths can be avoided by making the common base class as virtual base class.
Class A{….};Class B1:virtual public A{…};
Class B2:public virtual A{…};Class C:public B1,public B2{….};
Abstract ClassesAn abstract class is one that is not used to
create objects.It is designed only to act as a base class.
Constructors in Derived class
No parameterized constructor in base class: no need to define constructor in derived class.
If contains then there is a need to define ctor in derived class.
Usually we create objects of derived classes, it make sense to pass arguments to the base class constructor.
If both classes are having constructors, then the base constructor is executed first and then the constructor in the derived class is executed.
General SyntaxDerived-ctor (Arg1, n(argn)arg2,…argn, argd):base1(arg1),base2(arg2),….basen(argn){
//body of derived constructor}
D(int a1, int a2, int d1):B(a1,a2){d=d1;}
Using Constructors and Destructors in Derived Classes
Derived-class constructor Calls the constructor for its base class first to
initialize its base-class membersIf 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
Example 1:default in base no need of ctor in derivedClass A class B{ {int a; public:public: void display()A(){a=0;} {A::display();}void display() };{cout<<a;} void main()}; {B b1;
b1.display();}
Output is: 0
Example 2:if default ctor in derived Class A class B{ {int b;int a; public:public: B(){b=5;}
void display()A(){a=0;} {A::display();void display() cout<<b;}};{cout<<a;} void main()}; {B b1;
b1.display();}
Output is:0 5
Example 3Class A class B{ {int b;int a; public:public: B(){b=5;}A(){a=0;} void display()A(int m) {A::display();{a=m;} cout<<b;}};void display() {cout<<a;} void main()}; {B b1;
b1.display();}
Output:0 5
Example 4
Class A class B{ {int b;int a; public:public: B(){b=5;}A(){a=0;} B(int n){b=n;}A(int m) void display(){A::display();{a=m;} cout<<b;}};void display() {cout<<a;} void main()}; {B b1(10);
b1.display();}
Output is:0 10
Example 5Class A class B{ {int b;int a; public:public: B(){b=5;}A(){a=0;} B(int m,int n):A(m),b(n){}A(int m) void display(){A::display();{a=m;} cout<<b;}};void display() {cout<<a;} void main()}; {B b1(10,20);
b1.display();}
Multiple Inheritance with constructorsBase classes are constructed in the order in
which they appear in the declaration of the derived class.
ExampleClass D:public A, protected B, private C
Order of execution is:ABCD
Multilevel Inheritance with constructorsIn multilevel inheritance, the constructors
will be executed in the order of inheritance.
A
C
B
Order is
ABC
Execution of base class constructorsConstructors for virtual base classes are
invoked before any non-virtual base classes.
Class A:public virtual B, public C, public DClass A:public B, virtual public C, public DClass A:virtual public B, public C, virtual
public D
class A void show() void main()
{ { {
int a; cout<<b; C c1(4,5,6);
public: }}; c1.A::show();
A(int x) class C:public A, public Bc1.B::show();
{a=x;} { c1.show();
void show() int c; }
{cout<<a;} public:
}; C(int m, int n, int z):B(n),A(m),C(z)
class B {cout<<“objects initialized”;}
{int b; void show()
public: {cout<<c;}
B(int y) };
{b=y;
}
Case Study: Point, Circle, Cylinder
Define class PointDerive Circle
Derive Cylinder