Professional Documents
Culture Documents
Assignment: Write Is The Difference Between Inheritance and Polymorphism? Explain With C++ Examples
Assignment: Write Is The Difference Between Inheritance and Polymorphism? Explain With C++ Examples
Write is the difference between inheritance and polymorphism? Explain with C++
examples.
Answer
Inheritance
It is a part of object oriented programming paradigm.
It can be implemented in C++, Java, Python, and other object oriented
programming languages.
It is the method in which a new class is created that can take and use the
properties of an already existing class.
The already existing class is known as ‘parent/base class’ and the class that
uses this class is known as ‘child/derived class’.
It helps reuse the code.
It reduces the size of the code while implementing object oriented
programming.
Types of inheritance −
o Single inheritance
o Multi-level inheritance
o Multiple inheritance
o Hybrid inheritance
o Hierarchical inheritance
It can be used in pattern design.
Example
class base_class:
def __init__(self, f_name, l_name):
self.firstname = f_name
self.lastname = l_name
def print_it(self):
print(self.firstname, self.lastname)
print("An instance of 'base_class' is created")
my_instance = base_class("John", "Will")
print("A method 'print_it' is being called using the created instance")
my_instance.print_it()
Output
An instance of 'base_class' is created
A method 'print_it' is being called using the created instance
John Will
Polymorphism
‘Poly’ means multiple and ‘morph’ means forms.
It allows the object of the class to decide which form it has to take to work
with methods and attributes of the class.
Types of polymorphism −
Example
def add_vals(val_1, val_2, val_3 = 1):
my_result = val_1 + val_2 + val_3
return my_result
Inheritance allows, code reusability and the polymorphism is, the occurrence of
one function with different form. The basic difference between inheritance and
polymorphism is that inheritance allows the already existing code to be reused
again in a program, and polymorphism provides a mechanism to dynamically
decide what form of a function to be invoked.
Basic
Implementation
Forms
Categories
Example
The class 'table' can inherit the feature The class 'study_table' can also have
of the class 'furniture', as a 'table' is a function 'set_color()' and a class
'furniture'. 'Dining_table' can also have function
'set_color()' so, which form of the
set_color() function to invoke can be
decided at both, compile time and run
time.