SlideShare a Scribd company logo
1 of 42
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

Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Vineeta Garg
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member FunctionsMOHIT AGARWAL
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ pptKumar
 
Classes and objects
Classes and objectsClasses and objects
Classes and objectsNilesh Dalvi
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sqlÑirmal Tatiwal
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++Rabin BK
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++Muhammad Waqas
 
Object oriented programming concepts
Object oriented programming conceptsObject oriented programming concepts
Object oriented programming conceptsrahuld115
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functionsHarsh Patel
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default argumentsNikhil Pandit
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Access specifier
Access specifierAccess specifier
Access specifierzindadili
 

What's hot (20)

Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Packages - PL/SQL
Packages - PL/SQLPackages - PL/SQL
Packages - PL/SQL
 
Object oriented programming concepts
Object oriented programming conceptsObject oriented programming concepts
Object oriented programming concepts
 
C++ presentation
C++ presentationC++ presentation
C++ presentation
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
Access specifier
Access specifierAccess specifier
Access specifier
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 

Viewers also liked

Viewers also liked (13)

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 VariablesNilesh Dalvi
 
Pooja Sharma , BCA Third Year
Pooja Sharma , BCA Third YearPooja Sharma , BCA Third Year
Pooja Sharma , BCA Third YearDezyneecole
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
Daksh Sharma ,BCA 2nd Year
Daksh  Sharma ,BCA 2nd YearDaksh  Sharma ,BCA 2nd Year
Daksh Sharma ,BCA 2nd Yeardezyneecole
 
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 suImranAliQureshi3
 
OOP PPT 1.pptx
OOP PPT 1.pptxOOP PPT 1.pptx
OOP PPT 1.pptxlathass5
 
Virtual function
Virtual functionVirtual function
Virtual functionsdrhr
 
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 2Aadil 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 01Zafor Iqbal
 
classes & objects.ppt
classes & objects.pptclasses & objects.ppt
classes & objects.pptBArulmozhi
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and MethodsNilesh Dalvi
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxShaownRoy1
 
Pooja Sharma ,BCA 2nd Year
Pooja Sharma ,BCA 2nd YearPooja Sharma ,BCA 2nd Year
Pooja Sharma ,BCA 2nd Yeardezyneecole
 
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-13Abu Saleh
 
Object Oriented Programming Constructors & Destructors
Object Oriented Programming  Constructors &  DestructorsObject Oriented Programming  Constructors &  Destructors
Object Oriented Programming Constructors & Destructorsanitashinde33
 

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
 
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
 
OOP PPT 1.pptx
OOP PPT 1.pptxOOP PPT 1.pptx
OOP PPT 1.pptx
 
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 javaNilesh Dalvi
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception HandlingNilesh Dalvi
 
5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and IntefacesNilesh Dalvi
 
1. Overview of Java
1. Overview of Java1. Overview of Java
1. Overview of JavaNilesh Dalvi
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template LibraryNilesh Dalvi
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cppNilesh Dalvi
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops conceptsNilesh Dalvi
 

More from Nilesh Dalvi (11)

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
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
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

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxleah joy valeriano
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 

Recently uploaded (20)

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 

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