SlideShare a Scribd company logo
PolymorphismPolymorphism
By
Nilesh Dalvi
Lecturer, Patkar-Varde College.Lecturer, Patkar-Varde College.
http://www.slideshare.net/nileshdalvi01
Object oriented ProgrammingObject oriented Programming
with C++with C++
Polymorphism
• Polymorphism is the technique in which
various forms of a single function can be
defined and shared by various objects to
perform the operation.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Polymorphism
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Pointer
• A pointer is a memory variable that stores a
memory address. Pointers can have any
name that is legal for other variables and it
is declared in the same fashion like other
variables but it is always denoted by ‘*’
operator.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Pointer declaration
• Syntax:
data-type * pointer-mane;
• For example:
• int *x; //integer pointer, holds
//address of any integer variable.
• float *f; //float pointer, stores
//address of any float variable.
• char *y; //character pointer, stores
//address of any character variable.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Pointer declaration & initialization
int *ptr; //declaration.
int a;
ptr = &a; //initialization.
• ptr contains the address of a.
• We can also declare pointer variable to point
to another pointer,
int a, *ptr1, *ptr2;
ptr1 = &a;
ptr2 = &ptr1;
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• We can manipulate the pointer with
indirection operator i.e. ‘*’ is also known as
deference operator.
• Dereferencing a pointer allows us to get the
content of the memory location.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Manipulation of Pointer
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Manipulation of Pointer
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int *ptr;
ptr = &a;
cout <<"nDereferencing :: "<< *ptr <<endl;
*ptr = *ptr + a;
cout << a;
return 0;
}
• A pointer can be incremented(++) or
decremented(--).
• Any integer can be added to or subtracted
from a pointer.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Pointer Expressions and Arithmetic:
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Pointer Expressions and Arithmetic:
#include <iostream>
using namespace std;
int main()
{
int num [] = {56, 75, 22, 18, 90};
int *ptr;
ptr = &num[0]; // ptr = num;
cout << *ptr <<endl;
ptr++;
cout << *ptr <<endl;
ptr--;
cout << *ptr <<endl;
ptr = ptr + 2;
cout << *ptr <<endl;
ptr = ptr - 1;
cout << *ptr <<endl;
ptr += 3;
cout << *ptr <<endl;
ptr -=2;
cout << *ptr <<endl;
return 0;
}
• Pointer objects are useful in creating objects
at run-time.
• We can also use an object pointer to access
the public members of an object.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Pointer to objects
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Pointer to objects
#include <iostream>
using namespace std;
class item
{
int code;
float price;
public:
void getdata(int a, float b)
{
code = a;
price = b;
}
void show (void)
{
cout << code <<endl;
cout << price <<endl;
}
};
Pointer to objects
• We can also write ,
int main()
{
item x;
x.getdata(100, 75.6);
x.show();
item *ptr = &x;
ptr -> getdata(100, 75.6);
ptr ->show();
return 0;
}
(*ptr).show();//*ptr is an alias of x
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• We can also create objects using pointers
and new operator as follows:
• Statements allocates enough memory for
data members in the objects structure.
• We can create array of objects using
pointers,
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Pointer to objects
Item *ptr = new item;
Item *ptr = new item[10];
• Pointers can be declared to point base or
derived classes.
• Pointers to object of base class are type-
compatible with pointers to object of
derived class.
• Base class pointer can point to objects of
base and derived class.
• Pointer to base class object can point to
objects of derived classes whereas a pointer
to derived class object cannot point to
objects of base class.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Pointer to derived classes
Fig: Type-compatibility of base and derived class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Pointer to derived classes
• If B is a base class and D is a derived class from B,
then a pointer declared as a pointer to B can also
be pointer to D.
B *ptr;
B b;
D d;
ptr = &b;
• We can also write,
ptr = &d;
• Here, we can access only those members which are
inherited from B and not the member that
originally belonging to D.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Pointer to derived classes
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Pointer to derived classes
#include <iostream>
using namespace std;
class B
{
public:
int b;
void show()
{
cout << "b = " << b <<endl;
}
};
class D : public B
{
public:
int d;
void show()
{
cout << "d = " << d <<endl;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Pointer to derived classes
int main()
{
B *bptr;
B bobj;
bptr = &bobj;
bptr -> b = 100;
bptr ->show ();
D dobj;
bptr = &dobj;
bptr -> b = 200;
bptr ->show ();
D *dptr;
dptr = &dobj;
dptr -> d = 300;
dptr ->show ();
return 0;
}
Output:
b = 100
b = 200
d = 300
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Pointer to derived classes
#include <iostream>
using namespace std;
class Polygon
{
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
};
class Rectangle: public Polygon
{
public:
int area()
{ return width*height; }
};
class Triangle: public Polygon
{
public:
int area()
{ return width*height/2; }
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Pointer to derived classes
int main ()
{
Rectangle rect;
Triangle trgl;
Polygon * ppoly1 = &rect;
Polygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
Rectangle *rec = &rect;
cout << rec->area() << 'n';
cout << trgl.area() << 'n';
return 0;
}
• If there are member functions with same
name in base class and derived class, virtual
functions gives programmer capability to
call member function of different class by a
same function call depending upon different
context.
• This feature in C++ programming is known
as polymorphism which is one of the
important feature of OOP.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual functions
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual functions
#include <iostream>
using namespace std;
class B
{
public:
void display()
{ cout<<"Content of base class.n"; }
};
class D : public B
{
public:
void display()
{ cout<<"Content of derived class.n"; }
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual functions
int main()
{
B *b = new B;
D d;
b->display();
b = &d; /* Address of object d in pointer variable */
b->display();
return 0;
}
Output:
Content of base class.
Content of base class.
• If you want to execute the member function
of derived class then, you can declare
display() in the base class virtual which
makes that function existing in appearance
only but, you can't call that function.
• In order to make a function virtual, you have
to add keyword virtual in front of a function.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual functions
• The virtual functions should not be static
and must be member of a class.
• A virtual function may be declared as friend
for another class. Object pointer can access
virtual functions.
• Constructors cannot be declared as a virtual,
but destructor can be declared as virtual.
• The virtual function must be defined in
public section of the class. It is also possible
to define the virtual function outside the
class.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Rules for virtual functions
• It is also possible to return a value from
virtual function like other functions.
• The prototype of virtual functions in base
and derived classes should be exactly the
same.
– In case of mismatch, the compiler neglects the
virtual function mechanism and treats them as
overloaded functions.
• Arithmetic operation cannot be used with
base class pointer.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Rules for virtual functions
• If base class contains virtual function and if
the same function is not redefined in the
derived classes in that base class function is
invoked.
• The operator keyword used for operator
overloading also supports virtual
mechanism.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Rules for virtual functions
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual functions
#include <iostream>
using namespace std;
class B
{
public:
virtual void display() /* Virtual function */
{ cout<<"Content of base class.n"; }
};
class D1 : public B
{
public:
void display()
{ cout<<"Content of first derived class.n"; }
};
class D2 : public B
{
public:
void display()
{ cout<<"Content of second derived class.n"; }
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual functions
int main()
{
B *b = new B;
D1 d1;
D2 d2;
/* b->display(); // You cannot use this code here
because the function of base class is virtual. */
b = &d1;
b->display(); /* calls display() of class derived D1 */
b = &d2;
b->display(); /* calls display() of class derived D2 */
return 0;
}
Output:
Content of first derived class.
Content of second derived class.
• In above program, display( ) function of two
different classes are called with same code
which is one of the example of
polymorphism in C++ programming using
virtual functions.
• Remember, run-time polymorphism is
achieved only when a virtual function is
accessed through a pointer to the base class.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual functions
• If expression =0 is added to a virtual
function then, that function is becomes pure
virtual function.
• Note that, adding =0 to virtual function does
not assign value, it simply indicates the
virtual function is a pure function.
• If a base class contains at least one virtual
function then, that class is known as
abstract class.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Declaration of a Abstract Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Abstract Class
#include <iostream>
using namespace std;
class Shape /* Abstract class */
{
protected:
float l;
public:
void get_data() /* Note: this function is not virtual. */
{
cin>>l;
}
virtual float area() = 0; /* Pure virtual function */
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Abstract Class
class Square : public Shape
{
public:
float area()
{ return l*l; }
};
class Circle : public Shape
{
public:
float area()
{ return 3.14*l*l; }
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Abstract Class
Output :
Enter length to calculate area of a square: 2
Area of square: 4
Enter radius to calcuate area of a circle:3
Area of circle: 28.26
int main()
{
Shape *ptr;
Square s;
Circle c;
ptr = &s;
cout<<"Enter length to calculate area of a square: ";
ptr -> get_data();
cout<<"Area of square: "<<ptr ->area();
ptr = &c;
cout<<"nEnter radius to calcuate area of a circle:";
ptr -> get_data();
cout<<"Area of circle: "<<ptr ->area();
return 0;
}
• Consider a book-shop which sells both
books and videos-tapes.
• We can create media that stores the title
and price of a publication.
• We can then create two derived classes, one
for storing the number of pages in a book
and another for storing playing time of a
tape.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Implementation in practice
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Implementation in practice
Fig: class hierarchy for book shop
mediamedia
tapetapebookbook
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Abstract Class
#include <iostream>
using namespace std;
class media /* Abstract class */
{
protected:
char *title;
double price;
public:
media(char *s, double p)
{
title = new char [strlen(s)+1];
strcpy (title, s);
price = p;
}
virtual void display() = 0; /* Pure virtual function */
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Abstract Class
class book : public media
{
int pages;
public:
book(char *s, double p, int pg):media(s,p)
{
pages = pg;
}
void display()
{
cout << "Book details :" << endl;
cout << "Title : "<< title << endl;
cout << "Price : "<< price << endl;
cout << "No of pages: "<< pages << endl;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Abstract Class
class tape : public media
{
int duration;
public:
tape(char *s, double p, int dr):media(s,p)
{
duration = dr;
}
void display()
{
cout << "Tape details :" << endl;
cout << "Title : "<< title << endl;
cout << "Price : "<< price << endl;
cout << "Duration: "<< duration << endl;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Abstract Class
int main()
{
media *ptr;
book b("My Life....",12.22,200);
tape t("Tech Talks..",56.23,80);
ptr = &b;
ptr -> display ();
ptr = &t;
ptr -> display ();
return 0;
}
Output :
Book details :
Title : My Life....
Price : 12.22
No of pages: 200
Tape details :
Title : Tech Talks..
Price : 56.23
Duration: 80
Polymorphism

More Related Content

What's hot

Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
Data structures using c
Data structures using cData structures using c
Data structures using c
Prof. Dr. K. Adisesha
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
Haresh Jaiswal
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
File handling in c++
File handling in c++File handling in c++
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Dr Sukhpal Singh Gill
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Abhilash Nair
 
Java constructors
Java constructorsJava constructors
Java constructors
QUONTRASOLUTIONS
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
Nilesh Dalvi
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
Structure in C
Structure in CStructure in C
Structure in C
Kamal Acharya
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vineeta Garg
 
Introduction to c++ ppt 1
Introduction to c++ ppt 1Introduction to c++ ppt 1
Introduction to c++ ppt 1
Prof. Dr. K. Adisesha
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vishal Patil
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
Hitesh Kumar
 
3 data-types-in-c
3 data-types-in-c3 data-types-in-c
3 data-types-in-c
teach4uin
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
Nilesh Dalvi
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Maaz Hasan
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
Srinivas Narasegouda
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
Niloy Saha
 

What's hot (20)

Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Data structures using c
Data structures using cData structures using c
Data structures using c
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Structure in C
Structure in CStructure in C
Structure in C
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Introduction to c++ ppt 1
Introduction to c++ ppt 1Introduction to c++ ppt 1
Introduction to c++ ppt 1
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
3 data-types-in-c
3 data-types-in-c3 data-types-in-c
3 data-types-in-c
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 

Viewers also liked

Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
Nilesh Dalvi
 
14. Linked List
14. Linked List14. Linked List
14. Linked List
Nilesh Dalvi
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
Nilesh Dalvi
 
7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
Nilesh Dalvi
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++
Amresh Raj
 
11. Arrays
11. Arrays11. Arrays
11. Arrays
Nilesh Dalvi
 
10. Introduction to Datastructure
10. Introduction to Datastructure10. Introduction to Datastructure
10. Introduction to Datastructure
Nilesh Dalvi
 
13. Queue
13. Queue13. Queue
13. Queue
Nilesh Dalvi
 
12. Stack
12. Stack12. Stack
12. Stack
Nilesh Dalvi
 
Strings
StringsStrings
Strings
Nilesh Dalvi
 
Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
ForwardBlog Enewzletter
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
polymorphism
polymorphism polymorphism
polymorphism
Imtiaz Hussain
 
Constructor and destructor in c++
Constructor and destructor in c++Constructor and destructor in c++
Constructor and destructor in c++
Learn By Watch
 

Viewers also liked (14)

Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
 
14. Linked List
14. Linked List14. Linked List
14. Linked List
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++
 
11. Arrays
11. Arrays11. Arrays
11. Arrays
 
10. Introduction to Datastructure
10. Introduction to Datastructure10. Introduction to Datastructure
10. Introduction to Datastructure
 
13. Queue
13. Queue13. Queue
13. Queue
 
12. Stack
12. Stack12. Stack
12. Stack
 
Strings
StringsStrings
Strings
 
Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
polymorphism
polymorphism polymorphism
polymorphism
 
Constructor and destructor in c++
Constructor and destructor in c++Constructor and destructor in c++
Constructor and destructor in c++
 

Similar to Polymorphism

3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and Variables
Nilesh Dalvi
 
Pooja Sharma , BCA Third Year
Pooja Sharma , BCA Third YearPooja Sharma , BCA Third Year
Pooja Sharma , BCA Third Year
Dezyneecole
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 
Daksh Sharma ,BCA 2nd Year
Daksh  Sharma ,BCA 2nd YearDaksh  Sharma ,BCA 2nd Year
Daksh Sharma ,BCA 2nd Year
dezyneecole
 
OOP PPT 1.pptx
OOP PPT 1.pptxOOP PPT 1.pptx
OOP PPT 1.pptx
lathass5
 
Intro-OOP-PPT- an introduction to the su
Intro-OOP-PPT- an introduction to the suIntro-OOP-PPT- an introduction to the su
Intro-OOP-PPT- an introduction to the su
ImranAliQureshi3
 
Virtual function
Virtual functionVirtual function
Virtual function
sdrhr
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2
Aadil Ansari
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
Zafor Iqbal
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.ppt
BArulmozhi
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
Nilesh Dalvi
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
ShaownRoy1
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
rehan16091997
 
Pooja Sharma ,BCA 2nd Year
Pooja Sharma ,BCA 2nd YearPooja Sharma ,BCA 2nd Year
Pooja Sharma ,BCA 2nd Year
dezyneecole
 
advance-dart.pptx
advance-dart.pptxadvance-dart.pptx
advance-dart.pptx
christianmisikir
 
OOP in java
OOP in javaOOP in java
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Abu Saleh
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
Mufaddal Nullwala
 
Object Oriented Programming Constructors & Destructors
Object Oriented Programming  Constructors &  DestructorsObject Oriented Programming  Constructors &  Destructors
Object Oriented Programming Constructors & Destructors
anitashinde33
 

Similar to Polymorphism (20)

3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and Variables
 
Pooja Sharma , BCA Third Year
Pooja Sharma , BCA Third YearPooja Sharma , BCA Third Year
Pooja Sharma , BCA Third Year
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Daksh Sharma ,BCA 2nd Year
Daksh  Sharma ,BCA 2nd YearDaksh  Sharma ,BCA 2nd Year
Daksh Sharma ,BCA 2nd Year
 
OOP PPT 1.pptx
OOP PPT 1.pptxOOP PPT 1.pptx
OOP PPT 1.pptx
 
Intro-OOP-PPT- an introduction to the su
Intro-OOP-PPT- an introduction to the suIntro-OOP-PPT- an introduction to the su
Intro-OOP-PPT- an introduction to the su
 
Virtual function
Virtual functionVirtual function
Virtual function
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.ppt
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Pooja Sharma ,BCA 2nd Year
Pooja Sharma ,BCA 2nd YearPooja Sharma ,BCA 2nd Year
Pooja Sharma ,BCA 2nd Year
 
advance-dart.pptx
advance-dart.pptxadvance-dart.pptx
advance-dart.pptx
 
OOP in java
OOP in javaOOP in java
OOP in java
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Object Oriented Programming Constructors & Destructors
Object Oriented Programming  Constructors &  DestructorsObject Oriented Programming  Constructors &  Destructors
Object Oriented Programming Constructors & Destructors
 

More from Nilesh Dalvi

9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
8. String
8. String8. String
8. String
Nilesh Dalvi
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception Handling
Nilesh Dalvi
 
5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces
Nilesh Dalvi
 
2. Basics of Java
2. Basics of Java2. Basics of Java
2. Basics of Java
Nilesh Dalvi
 
1. Overview of Java
1. Overview of Java1. Overview of Java
1. Overview of Java
Nilesh Dalvi
 
Templates
TemplatesTemplates
Templates
Nilesh Dalvi
 
File handling
File handlingFile handling
File handling
Nilesh Dalvi
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
Nilesh Dalvi
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
Nilesh Dalvi
 

More from Nilesh Dalvi (10)

9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
8. String
8. String8. String
8. String
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception Handling
 
5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces
 
2. Basics of Java
2. Basics of Java2. Basics of Java
2. Basics of Java
 
1. Overview of Java
1. Overview of Java1. Overview of Java
1. Overview of Java
 
Templates
TemplatesTemplates
Templates
 
File handling
File handlingFile handling
File handling
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 

Recently uploaded

UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
S. Raj Kumar
 
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Leena Ghag-Sakpal
 
ZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptxZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptx
dot55audits
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
MJDuyan
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
Wahiba Chair Training & Consulting
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
ssuser13ffe4
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
haiqairshad
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
Solutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptxSolutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptx
spdendr
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
สมใจ จันสุกสี
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
Krassimira Luka
 

Recently uploaded (20)

UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
 
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
 
ZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptxZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptx
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
Solutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptxSolutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptx
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
 

Polymorphism

  • 1. PolymorphismPolymorphism By Nilesh Dalvi Lecturer, Patkar-Varde College.Lecturer, Patkar-Varde College. http://www.slideshare.net/nileshdalvi01 Object oriented ProgrammingObject oriented Programming with C++with C++
  • 2. Polymorphism • Polymorphism is the technique in which various forms of a single function can be defined and shared by various objects to perform the operation. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 4. Pointer • A pointer is a memory variable that stores a memory address. Pointers can have any name that is legal for other variables and it is declared in the same fashion like other variables but it is always denoted by ‘*’ operator. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 5. Pointer declaration • Syntax: data-type * pointer-mane; • For example: • int *x; //integer pointer, holds //address of any integer variable. • float *f; //float pointer, stores //address of any float variable. • char *y; //character pointer, stores //address of any character variable. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 6. Pointer declaration & initialization int *ptr; //declaration. int a; ptr = &a; //initialization. • ptr contains the address of a. • We can also declare pointer variable to point to another pointer, int a, *ptr1, *ptr2; ptr1 = &a; ptr2 = &ptr1; Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 7. • We can manipulate the pointer with indirection operator i.e. ‘*’ is also known as deference operator. • Dereferencing a pointer allows us to get the content of the memory location. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Manipulation of Pointer
  • 8. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Manipulation of Pointer #include <iostream> using namespace std; int main() { int a = 10; int *ptr; ptr = &a; cout <<"nDereferencing :: "<< *ptr <<endl; *ptr = *ptr + a; cout << a; return 0; }
  • 9. • A pointer can be incremented(++) or decremented(--). • Any integer can be added to or subtracted from a pointer. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Pointer Expressions and Arithmetic:
  • 10. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Pointer Expressions and Arithmetic: #include <iostream> using namespace std; int main() { int num [] = {56, 75, 22, 18, 90}; int *ptr; ptr = &num[0]; // ptr = num; cout << *ptr <<endl; ptr++; cout << *ptr <<endl; ptr--; cout << *ptr <<endl; ptr = ptr + 2; cout << *ptr <<endl; ptr = ptr - 1; cout << *ptr <<endl; ptr += 3; cout << *ptr <<endl; ptr -=2; cout << *ptr <<endl; return 0; }
  • 11. • Pointer objects are useful in creating objects at run-time. • We can also use an object pointer to access the public members of an object. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Pointer to objects
  • 12. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Pointer to objects #include <iostream> using namespace std; class item { int code; float price; public: void getdata(int a, float b) { code = a; price = b; } void show (void) { cout << code <<endl; cout << price <<endl; } };
  • 13. Pointer to objects • We can also write , int main() { item x; x.getdata(100, 75.6); x.show(); item *ptr = &x; ptr -> getdata(100, 75.6); ptr ->show(); return 0; } (*ptr).show();//*ptr is an alias of x Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 14. • We can also create objects using pointers and new operator as follows: • Statements allocates enough memory for data members in the objects structure. • We can create array of objects using pointers, Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Pointer to objects Item *ptr = new item; Item *ptr = new item[10];
  • 15. • Pointers can be declared to point base or derived classes. • Pointers to object of base class are type- compatible with pointers to object of derived class. • Base class pointer can point to objects of base and derived class. • Pointer to base class object can point to objects of derived classes whereas a pointer to derived class object cannot point to objects of base class. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Pointer to derived classes
  • 16. Fig: Type-compatibility of base and derived class Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Pointer to derived classes
  • 17. • If B is a base class and D is a derived class from B, then a pointer declared as a pointer to B can also be pointer to D. B *ptr; B b; D d; ptr = &b; • We can also write, ptr = &d; • Here, we can access only those members which are inherited from B and not the member that originally belonging to D. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Pointer to derived classes
  • 18. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Pointer to derived classes #include <iostream> using namespace std; class B { public: int b; void show() { cout << "b = " << b <<endl; } }; class D : public B { public: int d; void show() { cout << "d = " << d <<endl; } };
  • 19. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Pointer to derived classes int main() { B *bptr; B bobj; bptr = &bobj; bptr -> b = 100; bptr ->show (); D dobj; bptr = &dobj; bptr -> b = 200; bptr ->show (); D *dptr; dptr = &dobj; dptr -> d = 300; dptr ->show (); return 0; } Output: b = 100 b = 200 d = 300
  • 20. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Pointer to derived classes #include <iostream> using namespace std; class Polygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } }; class Rectangle: public Polygon { public: int area() { return width*height; } }; class Triangle: public Polygon { public: int area() { return width*height/2; } };
  • 21. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Pointer to derived classes int main () { Rectangle rect; Triangle trgl; Polygon * ppoly1 = &rect; Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); Rectangle *rec = &rect; cout << rec->area() << 'n'; cout << trgl.area() << 'n'; return 0; }
  • 22. • If there are member functions with same name in base class and derived class, virtual functions gives programmer capability to call member function of different class by a same function call depending upon different context. • This feature in C++ programming is known as polymorphism which is one of the important feature of OOP. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual functions
  • 23. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual functions #include <iostream> using namespace std; class B { public: void display() { cout<<"Content of base class.n"; } }; class D : public B { public: void display() { cout<<"Content of derived class.n"; } };
  • 24. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual functions int main() { B *b = new B; D d; b->display(); b = &d; /* Address of object d in pointer variable */ b->display(); return 0; } Output: Content of base class. Content of base class.
  • 25. • If you want to execute the member function of derived class then, you can declare display() in the base class virtual which makes that function existing in appearance only but, you can't call that function. • In order to make a function virtual, you have to add keyword virtual in front of a function. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual functions
  • 26. • The virtual functions should not be static and must be member of a class. • A virtual function may be declared as friend for another class. Object pointer can access virtual functions. • Constructors cannot be declared as a virtual, but destructor can be declared as virtual. • The virtual function must be defined in public section of the class. It is also possible to define the virtual function outside the class. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Rules for virtual functions
  • 27. • It is also possible to return a value from virtual function like other functions. • The prototype of virtual functions in base and derived classes should be exactly the same. – In case of mismatch, the compiler neglects the virtual function mechanism and treats them as overloaded functions. • Arithmetic operation cannot be used with base class pointer. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Rules for virtual functions
  • 28. • If base class contains virtual function and if the same function is not redefined in the derived classes in that base class function is invoked. • The operator keyword used for operator overloading also supports virtual mechanism. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Rules for virtual functions
  • 29. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual functions #include <iostream> using namespace std; class B { public: virtual void display() /* Virtual function */ { cout<<"Content of base class.n"; } }; class D1 : public B { public: void display() { cout<<"Content of first derived class.n"; } }; class D2 : public B { public: void display() { cout<<"Content of second derived class.n"; } };
  • 30. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual functions int main() { B *b = new B; D1 d1; D2 d2; /* b->display(); // You cannot use this code here because the function of base class is virtual. */ b = &d1; b->display(); /* calls display() of class derived D1 */ b = &d2; b->display(); /* calls display() of class derived D2 */ return 0; } Output: Content of first derived class. Content of second derived class.
  • 31. • In above program, display( ) function of two different classes are called with same code which is one of the example of polymorphism in C++ programming using virtual functions. • Remember, run-time polymorphism is achieved only when a virtual function is accessed through a pointer to the base class. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual functions
  • 32. • If expression =0 is added to a virtual function then, that function is becomes pure virtual function. • Note that, adding =0 to virtual function does not assign value, it simply indicates the virtual function is a pure function. • If a base class contains at least one virtual function then, that class is known as abstract class. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Declaration of a Abstract Class
  • 33. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Abstract Class #include <iostream> using namespace std; class Shape /* Abstract class */ { protected: float l; public: void get_data() /* Note: this function is not virtual. */ { cin>>l; } virtual float area() = 0; /* Pure virtual function */ };
  • 34. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Abstract Class class Square : public Shape { public: float area() { return l*l; } }; class Circle : public Shape { public: float area() { return 3.14*l*l; } };
  • 35. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Abstract Class Output : Enter length to calculate area of a square: 2 Area of square: 4 Enter radius to calcuate area of a circle:3 Area of circle: 28.26 int main() { Shape *ptr; Square s; Circle c; ptr = &s; cout<<"Enter length to calculate area of a square: "; ptr -> get_data(); cout<<"Area of square: "<<ptr ->area(); ptr = &c; cout<<"nEnter radius to calcuate area of a circle:"; ptr -> get_data(); cout<<"Area of circle: "<<ptr ->area(); return 0; }
  • 36. • Consider a book-shop which sells both books and videos-tapes. • We can create media that stores the title and price of a publication. • We can then create two derived classes, one for storing the number of pages in a book and another for storing playing time of a tape. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Implementation in practice
  • 37. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Implementation in practice Fig: class hierarchy for book shop mediamedia tapetapebookbook
  • 38. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Abstract Class #include <iostream> using namespace std; class media /* Abstract class */ { protected: char *title; double price; public: media(char *s, double p) { title = new char [strlen(s)+1]; strcpy (title, s); price = p; } virtual void display() = 0; /* Pure virtual function */ };
  • 39. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Abstract Class class book : public media { int pages; public: book(char *s, double p, int pg):media(s,p) { pages = pg; } void display() { cout << "Book details :" << endl; cout << "Title : "<< title << endl; cout << "Price : "<< price << endl; cout << "No of pages: "<< pages << endl; } };
  • 40. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Abstract Class class tape : public media { int duration; public: tape(char *s, double p, int dr):media(s,p) { duration = dr; } void display() { cout << "Tape details :" << endl; cout << "Title : "<< title << endl; cout << "Price : "<< price << endl; cout << "Duration: "<< duration << endl; } };
  • 41. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Abstract Class int main() { media *ptr; book b("My Life....",12.22,200); tape t("Tech Talks..",56.23,80); ptr = &b; ptr -> display (); ptr = &t; ptr -> display (); return 0; } Output : Book details : Title : My Life.... Price : 12.22 No of pages: 200 Tape details : Title : Tech Talks.. Price : 56.23 Duration: 80