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

PPT
Inheritance : Extending Classes
PPTX
07. Virtual Functions
PDF
Classes and objects
PPT
Abstract class in java
PPTX
Constructor in java
PPTX
Functions in c++
PPTX
Virtual function in C++ Pure Virtual Function
PPTX
Object oriented programming in python
Inheritance : Extending Classes
07. Virtual Functions
Classes and objects
Abstract class in java
Constructor in java
Functions in c++
Virtual function in C++ Pure Virtual Function
Object oriented programming in python

What's hot (20)

PPTX
Object oriented programming
PPTX
Oops concept in c++ unit 3 -topic 4
PPTX
Access modifier and inheritance
PPTX
Virtual base class
PDF
Constructor and Destructor
PPTX
Classes objects in java
PPTX
virtual function
PPTX
Static Data Members and Member Functions
PPTX
Structure of java program diff c- cpp and java
PPTX
Java constructors
PPTX
classes and objects in C++
PPTX
C++ concept of Polymorphism
PPTX
Inner classes in java
PDF
Java Serialization
PPTX
Friend function
PPT
Standard Template Library
PPT
Packages in java
PPTX
Member Function in C++
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Object oriented programming
Oops concept in c++ unit 3 -topic 4
Access modifier and inheritance
Virtual base class
Constructor and Destructor
Classes objects in java
virtual function
Static Data Members and Member Functions
Structure of java program diff c- cpp and java
Java constructors
classes and objects in C++
C++ concept of Polymorphism
Inner classes in java
Java Serialization
Friend function
Standard Template Library
Packages in java
Member Function in C++
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Ad

Viewers also liked (14)

PPT
14. Linked List
PPT
Input and output in C++
PPT
7. Multithreading
PPTX
Interoduction to c++
PPT
11. Arrays
PPT
10. Introduction to Datastructure
PPT
13. Queue
PPT
12. Stack
PPT
Strings
PPTX
Constructors & destructors
PPTX
Oop c++class(final).ppt
PPTX
polymorphism
PDF
Constructors and destructors
PPTX
Constructor and destructor in c++
14. Linked List
Input and output in C++
7. Multithreading
Interoduction to c++
11. Arrays
10. Introduction to Datastructure
13. Queue
12. Stack
Strings
Constructors & destructors
Oop c++class(final).ppt
polymorphism
Constructors and destructors
Constructor and destructor in c++
Ad

Similar to Polymorphism (20)

PPT
3. Data types and Variables
PDF
Pooja Sharma , BCA Third Year
PPT
Operator Overloading
PPT
Object Oriented Programming Concept.Hello
PDF
Daksh Sharma ,BCA 2nd Year
PPTX
Intro-OOP-PPT- an introduction to the su
PPTX
OOP PPT 1.pptx
PPTX
Virtual function
PPTX
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
PPSX
Object oriented programming 2
PDF
C Sharp: Basic to Intermediate Part 01
PPT
classes & objects.ppt
PPTX
C++ Intro C++ Intro C++ Intro C++ Intro C++ Intro
PPT
4. Classes and Methods
PPTX
Introduction to Fundamental of Class.pptx
PPTX
Lecture-10_PHP-OOP.pptx
PPT
Oops lecture 1
PPTX
3.Syntax.pptx for oops programing language
PDF
Pooja Sharma ,BCA 2nd Year
PPTX
advance-dart.pptx
3. Data types and Variables
Pooja Sharma , BCA Third Year
Operator Overloading
Object Oriented Programming Concept.Hello
Daksh Sharma ,BCA 2nd Year
Intro-OOP-PPT- an introduction to the su
OOP PPT 1.pptx
Virtual function
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Object oriented programming 2
C Sharp: Basic to Intermediate Part 01
classes & objects.ppt
C++ Intro C++ Intro C++ Intro C++ Intro C++ Intro
4. Classes and Methods
Introduction to Fundamental of Class.pptx
Lecture-10_PHP-OOP.pptx
Oops lecture 1
3.Syntax.pptx for oops programing language
Pooja Sharma ,BCA 2nd Year
advance-dart.pptx

More from Nilesh Dalvi (10)

PPT
9. Input Output in java
PPT
8. String
PPT
6. Exception Handling
PPT
5. Inheritances, Packages and Intefaces
PPT
2. Basics of Java
PPT
1. Overview of Java
PPT
Templates
PPT
File handling
PDF
Introduction to cpp
PDF
Introduction to oops concepts
9. Input Output in java
8. String
6. Exception Handling
5. Inheritances, Packages and Intefaces
2. Basics of Java
1. Overview of Java
Templates
File handling
Introduction to cpp
Introduction to oops concepts

Recently uploaded (20)

PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Classroom Observation Tools for Teachers
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Business Ethics Teaching Materials for college
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Pharma ospi slides which help in ospi learning
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Pre independence Education in Inndia.pdf
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
master seminar digital applications in india
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
2.FourierTransform-ShortQuestionswithAnswers.pdf
Classroom Observation Tools for Teachers
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Business Ethics Teaching Materials for college
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Microbial diseases, their pathogenesis and prophylaxis
Pharma ospi slides which help in ospi learning
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Pre independence Education in Inndia.pdf
PPH.pptx obstetrics and gynecology in nursing
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
human mycosis Human fungal infections are called human mycosis..pptx
O5-L3 Freight Transport Ops (International) V1.pdf
master seminar digital applications in india
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra

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