Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 13

Inheritance

The advantage of making a new class a subclass is that it will


inherit attributes and methods of its parent class (also called
the superclass).

 Subclasses extend existing classes in three ways:


 By defining new (additional) attributes and methods.
 By overriding (changing the behavior) existing attributes and
methods.
 By hiding existing attributes and methods.

1-1
INHERITANCE
What is Inheritance in Object Oriented Programming?
Inheritance is the procedure in which one class inherits the
attributes and methods of another class. The class whose
properties and methods are inherited is known as the Parent
class (Base Class).
And the class that inherits the properties from the parent class
is the Child class (Derived Class).
(Along with the inherited properties and methods, a child class
can have its own properties and methods.)

1-2
Syntax to understand
class parent_class:
body of parent class

class child_class( parent_class):


body of child class

1-3
EXAMPLE
The derived class inherits the features from the base class and
can have additional features of its own. For example,

class Animal {
// eat() function
// sleep() function
};
class Dog : public Animal {
// bark() function
};

1-4
IS-A RELATIONSHIP
Inheritance is an is-a relationship. We use inheritance only if an
is-a relationship is present between the two classes.

Here are some examples:

A car is a vehicle.
Orange is a fruit.
A surgeon is a doctor.
A dog is an animal.

1-5
1-6
PROGRAM TO UNDERSTAND THE CONCEPT

1-7
PROGRAM TO UNDERSTAND THE CONCEPT

1-8
PROGRAM TO UNDERSTAND THE CONCEPT

1-9
MODES OF INHERITANCE
There are 3 modes of inheritance:
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.
[It can be modified by methods associated with any class
(violates encapsulation)]
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.
1 - 10
MODES OF INHERITANCE
Private Mode:
[It can’t be accessed by other objects.]

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.

1 - 11
1 - 12
1 - 13

You might also like