You are on page 1of 33

Inheritance

Inheritance
• One of the most important concepts in object-oriented programming is
that of inheritance.
• Inheritance allows us to define a class in terms of another class, which
makes it easier to create and maintain an application.
• This also provides an opportunity to reuse the code functionality and fast
implementation.
• When creating a class, instead of writing completely new data members
and member functions, the programmer can designate that the new class
should inherit the members of an existing class.
• The idea of inheritance implements the is a relationship.
example,
• mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well
and so on.
• Inheritance is a mechanism for building class types from existing class types
Reusability
• Reusability--building new components by utilising existing
components- 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.
• This mechanism of deriving a new class from existing/old
class is called “inheritance”.
Contd.
• The old class is known as
– base class
– super class
– parent class
A base class is a previously defined class that is used to define new classes
• The new class is known as
– sub class
– derived class
– child class.
A derived class inherits all the data and function members of a base class (in
addition to its explicitly declared members.)

• The derived class


– inherits from the parent all
• characteristics
• properties
• capabilities
– can modify or extend inherited abilities
Examples

Base class Derived classes


Student GraduateStudent
UndergraduateStudent
Shape Circle
Triangle
Rectangle
Loan CarLoan
HomeImprovementLoan
MortgageLoan
Employee FacultyMember
StaffMember
Account CheckingAccount
SavingsAccount
Contd.
A derived class inherits all base class methods
with the following exceptions:
• Constructors, destructors and copy
constructors of the base class.
• The friend functions of the base class.
Rules for building a class hierarchy
• Derived classes are special cases of base classes
• A derived class can also serve as a base class for new
classes.
• There is no limit on the depth of inheritance allowed
in C++ (as far as it is within the limits of your
compiler)
• It is possible for a class to be a base class for more
than one derived class
Different forms of inheritance
• 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)
• Multi-path inheritance (inheritance of some
properties from two sources).
Single Inheritance
• A derived class with only one base
class, is called Single Inheritance.
class ABC : public PQR
{ A

members of ABC
};
B
Multiple Inheritance
• A derived class with several
base classes, is called multiple
Inheritance.
class A : public B, public C C B
{
members of A
};
A
Hierarchical Inheritance
• The properties of one class may be
inherited by more than one class is
called hierarchical Inheritance.
class A : public B
{ B
members of A
};
class C : public B
{ A C
members of B
};
Multilevel Inheritance
• The mechanism of deriving a class from another
derived class is known as multilevel Inheritance.
class B : public A
A
{
members of B
}; B
class C : public B
{
members of C
C
};
Hybrid Inheritance
• The hybrid Inheritance is a combination of all
types of Inheritance.
B

C
Multipath Inheritance
A
i

B C
I,j I,k

D
i,j,k,
sum
Example
class Shape // Derived class
{ class Rectangle: public Shape
public: {
void setWidth(int w) public:
{ int getArea()
width = w; {
} return (width * height);
void setHeight(int h) }
{ };
height = h; int main(void)
} {
protected: Rectangle Rect;
int width; Rect.setWidth(5);
int height; Rect.setHeight(7);
}; // Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
Access Control and Inheritance
• A derived class can access all the non-private members of
its base class.
• Thus base-class members that should not be accessible to
the member functions of derived classes should be declared
private in the base class.

Access public protected private


Same class yes yes yes
Derived classes yes yes no
Outside classes yes no no
Access Rights of Derived Classes
Type of Inheritance

private protected public


for Members
Access Control

private - - -
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
OVERRIDING
• If we inherit a class into the derived class and provide a
definition for one of the base class's function again inside the
derived class, then that function is said to be overridden,
and this mechanism is called Function Overriding
• Function that is redefined must have exactly the same
declaration in both base and derived class, that means same
name, same return type and same parameter list.
• The child class provides alternative implementation for
parent class method.
• The key benefit of overriding is the ability to define behavior
that's specific to a particular subclass type.
Overloading vs. Overriding
• Overloading deals with multiple methods in the same class
with the same name but different signatures

• Overriding deals with two methods, one in a parent class and


one in a child class, that have the same signature

• Overloading lets you define a similar operation in different


ways for different data

• Overriding lets you define a similar operation in different ways


for different object types
Ambiguous in multiple inheritance
class A
{
public:
void show(){cout<<"A";} c.show() will invoke class C
}; function
class B But if no show() function is there in
{
public: class C – then there will be an
void show() { cout<<"B"; } ambiguity – which base class
}; function is to be invoked
/* class C is multiple derived from its superclass A and
B */
class C:public A, public B Use scope resolution operator to
{ explicitly specify which base class's
public : member function is to be invoked.
void show( ) { count<<“C”;}
};
Like,
int main() c.A::show();
{ C:B::show();
C c;
c.show();
}
Multipath Ambiguity
• An ambiguity can arise when several paths exist to
a class from the same base class.
• This means that a child class could have duplicate
sets of members inherited from a single base class.
• C++ solves this issue by introducing a virtual base
class.
• When a class is made virtual, necessary care is
taken so that the duplication is avoided regardless
of the number of paths that exist to the child class.
Virtual Base Class
class A int main()
{
{
public:
D ob;
int i;
}; ob.i = 10; //only one copy of i is inherited.
class B : virtual public A ob.j = 20;
{ ob.k = 30;
public: ob.sum = ob.i + ob.j + ob.k;
int j; cout << “Value of i is : ”<< ob.i<<”\n”;
}; cout << “Value of j is : ”<< ob.j<<”\n”;
class C: public virtual A cout << “Value of k is :”<< ob.k<<”\n”;
{ cout << “Sum is : ”<< ob.sum <<”\n”;
public:
int k; return 0;
}; }
class D: public B, public C
{
•The keywords virtual and public may be
public:
int sum; used in any order
};
Constructors in Derived Classes
• When an object of a derived class is created,
the constructor of the object must first
explicitly call the constructor of the base class.
• This is the same as constructor- initializer.
• An object of a derived class can be treated as
an object of its base class.
• The reverse is not true.
Why use the
constructor-initializer?
• If any base class contains a constructor with
arguments, then it is mandatory for the derived
class to have a constructor and pass arguments to
the base class constructor.
• Without it, the default constructor for the base
class would be called, which would then have to be
followed by calls to access functions to set specific
data members.
• A constructor initailizer is therefore more efficient.
Constructors and Destructors in Base and
Derived Classes
• Derived classes can have their own constructors
and destructors
• When an object of a derived class is created,
the base class’s constructor is executed first,
followed by the derived class’s constructor
• When an object of a derived class is destroyed,
its destructor is called first, then that of the
base class
Passing Arguments to
Base Class Constructor
• Allows selection between multiple base class
constructors
• Can also be done with inline constructors
• Must be done if base class has no default
constructor
• Specify arguments to base constructor on
derived constructor heading:
Example
class base1 {
protected: class derived: public base1, public base2 {
int i; int j; //beta1 is init
first
public:
public:
base1(int x) {
derived(int x, int y, int z): base2(z), base1(y){ //fn calls
i=x;
j=x;
cout << "Constructing base1\n"; cout << "Constructing derived\n";
} }
~base1() { ~derived() {
cout << "Destructing base1\n"; cout << "Destructing derived\n";
} }
}; void show() {
class base2 { cout << i << " " << j << " " << k << "\n";
protected: }
int k; };
public: int main()
{
base2(int x) {
derived ob(3, 4, 5);
k=x;
ob.show();
cout << "Constructing base2\n";
return 0;
} }
~base2() {
cout << "Destructing base2\n"; • Part after : is known as initialisation section
} • Base2(x+y) – exp can be given
};
Contd.
• A derived class can call a constructor defined
by its base class by using an expanded form of
the derived class’ constructor declaration.
• The base class are constructed in the order in
which they appear in the declaration of the
derived class.
• In multilevel inheritance, the constructors will
be executed in the order of inheritance.
Execution of the base class constructor
Destructor Function
• Destructors are called implicitly starting with
the last derived class and moving in the
direction of the base class.

You might also like