Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
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.
Polymorphism.Difference between Inheritance & Polymorphism
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
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 t
line sum = a+b will not create any problem as both the data types i.e, float and sum are predefin
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
Polymorphism.Difference between Inheritance & Polymorphism
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
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;
Polymorphism.Difference between Inheritance & Polymorphism
Polymorphism.Difference between Inheritance & Polymorphism
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 a
functions from outside the class.
◦ A friend function can access the private and protected data of a class. We declare a frie
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 frien
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 c
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;
}

More Related Content

Polymorphism.Difference between Inheritance & Polymorphism

  • 1. OBJECT-ORIENTED PROGRAMMING (OOP) Week – 04 Lecturer:Sobia Iftikhar
  • 2. 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
  • 3. 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
  • 5. 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.
  • 6. 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.
  • 8. 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.
  • 9. 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.
  • 10. 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).
  • 11. Type of Polymorphism ◦Static / Compile time polymorphism ◦Dynamic / Run time polymorphism
  • 12. 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.
  • 13. 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; }
  • 14. 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.
  • 15. 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; }
  • 16. 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.
  • 18. 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.
  • 19. 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.
  • 20. What are the Operators? Airthemetic Operators: +, -, *, /, %. Relational Operators: ==, !=, <=, >=. Bitwise Operators: |,&, <<, >>. Assignmnet Operators: +=, -=, *=, /=. Logical Operators: ||, &&, !. Other Operators: sizeof, typeid
  • 21. Operator Overloading Here let’s see the example of operator overloading. Since we know the use of the ‘+’ operator is 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 t line sum = a+b will not create any problem as both the data types i.e, float and sum are predefin objection as the + operator knows what to do with the pre-defined data types.
  • 22. 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
  • 23. 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.
  • 24. Syntax-Operator Overloading Overloaded operators are functions with special names: the keyword "operator" followed by the symbol for the operator being defined.
  • 27. Two types of operator overloading One operand: ++ -- Two Operand a*b unary operator overloading Binary operator overloading
  • 28. 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--.
  • 30. Unary Operator Example 02 Count count1, result; // Error result = ++count1; Count operator ++ () { // code } Count operator ++ (int) { // code }
  • 31. Return Value from Operator Function (++ Operator) Example 03
  • 33. Binary Operator ◦ In binary operator overloading function, there should be one argument to be passed. It 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;
  • 39. 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,
  • 40. Friend Function ◦ There is a feature in C++ called friend functions that break this rule and allow us to a functions from outside the class. ◦ A friend function can access the private and protected data of a class. We declare a frie the friend keyword inside the body of the class.
  • 41. 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; }
  • 42. 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.
  • 43. 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 frien 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 c friend class. This means that ABC can access the private members of XYZ, friend class ABC;
  • 44. 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; }