Polymorphism.Difference between �Inheritance & Polymorphism

114 views 44 slides Jun 12, 2024
Slide 1
Slide 1 of 44
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44

About This Presentation

Polymorphism in Object-Oriented Programming (OOP) allows objects of different classes to be treated as objects of a common superclass. It enables a single interface to represent different underlying forms (data types). There are two main types of polymorphism:

Compile-time polymorphism (static bind...


Slide Content

OBJECT-ORIENTED PROGRAMMING (OOP) Week – 04 Lecturer:Sobia Iftikhar

Exercise Create two classes named Mammals and MarineAnimals. Create another class named BlueWhale which inherits both the above classes. Now, create a function in each of these classes which prints "I am mammal", "I am a marine animal" and "I belong to both the categories: Mammals as well as Marine Animals" respectively. Now, create an object for each of the above class and try calling 1 - function of Mammals by the object of Mammal 2 - function of MarineAnimal by the object of MarineAnimal 3 - function of BlueWhale by the object of BlueWhale 4 - function of each of its parent by the object of BlueWhale Types of Inheritance = ?? Write a Basic Sekeletone

Exercise Create a base class named Person with name, age, and gender as its data members. Define a constructor to initialize the data members and a function display() to display the details of the person. Create a derived class named Employee which inherits Person class. Define empid and salary as its data members. Define a constructor to initialize the data members and override the display() function to display the details of the employee. Create another derived class named Manager which inherits Employee class. Define department as its data member. Define a constructor to initialize the data members and override the display() function to display the details of the manager. Create an object for Person, Employee, and Manager classes and call their display() functions. Types of Inheritance = ?? Write a Basic Sekeletone

Data Code Hiding

Polymorphism Polymorphism is derived from 2 Greek words:  poly  and morphs. The word "poly" means many and  morphs  means forms. So polymorphism means many forms. Polymorphism is a feature of  OOPs  that allows the object to behave differently in different conditions. we can define polymorphism as the ability of a message to be displayed in more than one form. First concept given by Hindley and Milner. The basic idea behind the polymorphism is that compiler does not which function to call at compile time.

Polymorphism-contd. A real-life example of polymorphism, a person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. So the same person posses different behavior in different situations. This is called polymorphism.

Polymorphism-contd.

Real life example of Polymorphism Suppose if you are in class room that time you behave like a student, when you are in market at that time you behave like a customer, when you at your home at that time you behave like a son or daughter, Here one person have different-different behaviors.

Polymorphism Importance Polymorphism saves the programmer a lot of time in re-creating code. You don't want to have to write completely different modules for every possible permutation. For example, if you had methods for tree growth, it would be hard to have to write a specific growth method for maple, spruce, pine, etc. Instead, you can have a growth function that spans across all tree types.

Difference between Inheritance & Polymorphism S.NO INHERITANCE POLYMORPHISM 1. Inheritance is one in which a new class is created (derived class) that inherits the features from the already existing class(Base class). Whereas polymorphism is that which can be defined in multiple forms. 2. It is basically applied to classes. Whereas it is basically applied to functions or methods. 3. Inheritance supports the concept of reusability and reduces code length in object-oriented programming. Polymorphism allows the object to decide which form of the function to implement at compile-time (overloading) as well as run-time (overriding). 4. Inheritance can be single, hybrid, multiple, hierarchical and multilevel inheritance. Whereas it can be compiled-time polymorphism (overload) as well as run-time polymorphism (overriding).

Type of Polymorphism Static / Compile time polymorphism Dynamic / Run time polymorphism

Static / Compile time polymorphism It is also called Early Binding It happens where more than one methods share the same name with different parameters or signature and different return type. It is  known  as Early Binding because the  compiler  is aware of the functions with same name and also which overloaded function is to be  called  is known  at  compile time.

Static / Compile time polymorphism using namespace std; class Geeks { public: // function with 1 int parameter void func(int x) { cout << "value of x is " << x << endl; } // function with same name but 1 double parameter void func(double x) { cout << "value of x is " << x << endl; } // function with same name and 2 int parameters void func(int x, int y) { cout << "value of x and y is " << x << ", " << y << endl; } }; int main() { Geeks obj1; // Which function is called will depend on the parameters passed // The first 'func' is called obj1.func(7); // The second 'func' is called obj1.func(9.132); // The third 'func' is called obj1.func(85,64); return 0; }

Dynamic / Run time polymorphism This refers to the entity which changes its form depending on circumstances at runtime. Method Overriding uses runtime Polymorphism. Runtime Polymorphism is done using virtual and inheritance. It is also called Late Binding.

Dynamic / Run time polymorphism include <bits/stdc++.h> using namespace std; class base { public: void print () { cout<< "print base class" <<endl; } void show () { cout<< "show base class" <<endl; } }; class derived:public base { public: void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly { cout<< "print derived class" <<endl; } void show () { cout<< "show derived class" <<endl; } }; //main function int main() { base *bptr; derived d; bptr = &d; //virtual function, binded at runtime (Runtime polymorphism) bptr->print(); // Non-virtual function, binded at compile time bptr->show(); return 0; }

Virtual Function If it is necessary to use a single pointer to refer to all the different classes’ objects. This is because we will have to create a pointer to the base class that refers to all the derived objects.  But, when the base class pointer contains the derived class address, the object always executes the base class function. For resolving this problem, we use the virtual function.

The vtable for the base class is straightforward. In the case of the derived class, only function1_virtual is overridden. Hence we see that in the derived class vtable, function pointer for function1_virtual points to the overridden function in the derived class. On the other hand function pointer for function2_virtual points to a function in the base class. Thus in the above program when the base pointer is assigned a derived class object, the base pointer points to _vptr of the derived class. So when the call b->function1_virtual() is made, the function1_virtual from the derived class is called and when the function call b->function2_virtual() is made, as this function pointer points to the base class function, the base class function is called.

Case-Study Define a class batsman with the following specifications: Private members: bcode                            4 digits code number bname                           20 characters innings, notout, runs      integer type batavg                           it is calculated according to the formula –                                      batavg =runs/(innings-notout) calcavg()                       Function to compute batavg Public members: readdata()                      Function to   accept value from bcode, name, innings, notout and invoke the function   calcavg() displaydata()                  Function to display the data members on the screen.

What are the Operators? Airthemetic Operators: +, -, *, /, %. Relational Operators: ==, !=, <=, >=. Bitwise Operators: |,&, <<, >>. Assignmnet Operators: +=, -=, *=, /=. Logical Operators: ||, &&, !. Other Operators: sizeof, typeid

Operator Overloading Here let’s see the example of operator overloading. Since we know the use of the ‘+’ operator is addition. For Example: float a; int b, sum; sum = a+b; In the above example we can see that a is a float type variable whereas b and sum are integer type variables so the line sum = a+b will not create any problem as both the data types i.e, float and sum are predefined so there will be no objection as the + operator knows what to do with the pre-defined data types.

Operator Overloading You can redefine or overload most of the built-in operators available in C++. Thus, a programmer can use operators with user-defined types as well. 5 5 10 obj1 ?? obj2 Compiler Error 10 10 Numbers Objects Can add

ERROR the line will give an error as we do not know what to do with objects of a user-defined class we are not performing operations on predefined data types we are performing operations on user-defined classes and objects. In these types of scenarios operator overloading in C++ comes into play as we can define the use case and function of operators in the class itself.

Syntax-Operator Overloading Overloaded operators are functions with special names: the keyword "operator" followed by the symbol for the operator being defined.

Function Calling

Two types of operator overloading One operand: ++ -- Two Operand a*b unary operator overloading Binary operator overloading

Unary Operator The unary operators operate on a single operand and following are the examples of Unary operators − The increment (++) and decrement (--) operators. The unary minus (-) operator. The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometime they can be used as postfix as well like obj++ or obj--.

Unary Operator Example 01

Unary Operator Example 02 Count count1, result; // Error result = ++count1; Count operator ++ () { // code } Count operator ++ (int) { // code }

Return Value from Operator Function (++ Operator) Example 03

Unary Operator

Binary Operator  In binary operator overloading function, there should be one argument to be passed. It is overloading of an operator operating on two operands. Let’s take the same example of class Distance, but this time, add two distance objects. d3 = d1 + d2; 

Example

Overloadable Operators

Non-overload-able Operators

Friend Function Data hiding is a fundamental concept of object-oriented programming. It restricts the access of private members from outside of the class. Similarly, protected members can only be accessed by derived classes and are inaccessible from outside. For example,

Friend Function There is a feature in C++ called  friend functions  that break this rule and allow us to access member functions from outside the class. A friend function can access the private and protected data of a class. We declare a friend function using the friend keyword inside the body of the class.

Working of friend Function-example #include <iostream> using namespace std; class Distance { private: int meter; // friend function friend int addFive(Distance); public: Distance() : meter(0) {} }; // friend function definition int addFive(Distance d) { //accessing private members from the friend function d.meter += 5; return d.meter; } int main() { Distance D; cout << "Distance: " << addFive(D); return 0; }

Friend Function cont’d Friend function must be declared with  friend  keyword. Friend function must be declare in all the classes from which we need to access private or protected members. Friend function will be defined outside the class without specifying the class name. Friend function will be invoked like normal function, without any object.

Function Class A  friend class  is a class that can access the private and protected members of a class in which it is declared as  friend . This is needed when we want to allow a particular class to access the private and protected members of a class. For example: we have two classes XYZ and ABC. The XYZ class has two private data members ch and num, this class declares ABC as friend class. This means that ABC can access the private members of XYZ, friend class ABC;

Working of friend Class-example #include <iostream> using namespace std; class XYZ { private: char ch='A'; int num = 11; public: friend class ABC; }; class ABC { public: void disp(XYZ obj){ cout<<obj.ch<<endl; cout<<obj.num<<endl; } }; int main() { ABC obj; XYZ obj2; obj.disp(obj2); return 0; }