SlideShare una empresa de Scribd logo
1 de 12
1
Polymorphism
• It simply means ‘one name, multiple forms’.
• We have already seen how the concepts of
polymorphism implemented using overloaded
function.
• The overloaded member function are selected
for invoking by matching arguments.
• This information is known to the compiler at
compile time and it is known as early binding .
Also known as compile time polymorphism.
#include <iostream.h>
class A
{
public :
float sum() {
return 10;
}
float sum(float i, float j,float k) {
return i+j+k;
}
};
class B : public A
{
public:
using A::sum;
float sum(float i) {
return i;
}
float sum(float i, int j) {
return i+j;
}
};
void main()
{
B calculate;
cout<<calculate.sum(25.5)<<endl;
cout<<calculate.sum(4.5,5)<<endl;
cout<<calculate.sum(4.5,3.5,2.5)<<endl;
cout<<calculate.sum()<<endl;
}
Output
25.5
9.5
10.5
10
3
• Consider the situation where the function name and
prototype is same in both the base and derived classes.
class A {
int x;
public:
void show(){…..}
};
class B : public A {
public:
void show(){…..}
};
• Since the prototype is same, function is not overloaded.
• Virtual function and pointer are used to invoke appropriate
member function while the program is running and it is
known as late binding .
• Also known as runtime polymorphism.
‫وائل‬
‫قصاص‬ 4
// pointers to base class
#include <iostream.h>
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b) {
width=a; height=b;
}
};
class CRectangle : public CPolygon {
public:
int area (void){ return (width * height); }
};
class CTriangle: public CPolygon {
public:
int area (void){
return (width * height / 2);
}
};
int main () {
CRectangle rect;
CTriangle trgl;
CPolygon * p1 = &rect;
CPolygon * p2 = &trgl;
p1->set_values (4,5);
p2->set_values (4,5);
cout << rect.area() << endl;
cout << trgl.area() << endl;
return 0;}
20
10
Code
• The function main creates two pointers that point to objects of class
CPolygon, that are *p1 and *p2. These are assigned to the addresses
of rect and trgl, and because they are objects of classes derived
from CPolygon they are valid assignations.
• The only limitation of using *p1 and *p2 instead of rect and trgl is
that both *p1 and *p2 are of type CPolygon* and therefore we can
only refer to the members that CRectangle and CTriangle inherit
from CPolygon. For that reason when calling the area() members
we have not been able to use the pointers *p1 and *p2.
• To make it possible for the pointers to class CPolygon to admit area
() as a valid member, this should also have been declared in the base
class and not only in its derived ones.
6
Virtual members
• In order to declare an element of a class which
we are going to redefine in derived classes we
must precede it with the keyword virtual so
that the use of pointers to objects of that class
can be suitable.
‫وائل‬
‫قصاص‬ 7
#include <iostream.h>
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b) {
width=a; height=b;
}
virtual int area (void) { return (0); }
};
class CRectangle: public CPolygon {
public:
int area (void){
return (width * height);
}
};
class CTriangle: public CPolygon {
public:
int area (void) {
return (width * height / 2);
}
};
int main () {
CRectangle rect;
CTriangle trgl;
CPolygon poly;
CPolygon * p1 = &rect;
CPolygon *p2=&trgl;
CPolygon * p3 = &poly;
p1->set_values(4,5);
p2->set_values(4,5);
p3->set_values (4,5);
cout << p1->area() << endl;
cout << p2->area() << endl;
cout << p3->area() << endl;}
20
10
0
• The three classes (CPolygon, CRectangle and CTriangle) have the
same members: width, height, set_values() and area().
• area() has been defined as virtual because it is later redefined in
derived classes. You can verify if you want that if you remove this
word (virtual) from the code and then you execute the program the
result will be 0 for the three polygons instead of 20,10,0. That is
because instead of calling the corresponding area() function for
each object (CRectangle::area(), CTriangle::area() and
CPolygon::area(), respectively), CPolygon::area() will be called
for all of them since the calls are via a pointer to CPolygon.
• Therefore, what the word virtual does is to allow a member of a
derived class with the same name as one in the base class be suitably
called when a pointer to it is used
Abstract base classes
• Abstract classes are similar to the class CPolygon of our previous example.
The only difference is that in our previous example we have defined a valid
area() function for objects that were of class CPolygon (like object poly),
whereas in an abstract base class we could have simply left without
defining this function by appending = 0 to the function declaration.
• The class CPolygon could have been thus:
// abstract class CPolygonclass
CPolygon {
protected:
int width, height;
public:
void set_values(int a, int b){
width=a; height=b;
}
virtual int area (void) = 0;
};
• This type of function is called a pure virtual function, and all classes
that contain a pure virtual function (do-nothing function) are
considered abstract base classes.
• The greatest difference of an abstract base class is that instances
(objects) of it cannot be created, but we can create pointers to them.
Therefore a declaration likes:
CPolygon poly; // incorrect
CPolygon * ppoly1; //correct
• This is because the pure virtual function that it includes is not defined
and it is impossible to create an object if it does not have all its
members defined. A pointer that points to an object of a derived class
where this function has been defined is perfectly valid.
• The main objective of an abstract base class is to provide some traits to
the derived classes and to create a base pointer required for achieving
run time polymorphism.
#include <iostream.h>
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area (void) = 0;
};
class CRectangle: public CPolygon {
public:
int area (void)
{return (width * height); }
};
class CTriangle: public CPolygon {
public:
int area (void)
{return (width * height / 2); }
};
int main () {
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = &rect;
CPolygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << ppoly1->area() << endl;
cout << ppoly2->area() << endl;
return 0;
}
20
10
‫وائل‬
‫قصاص‬ 12
#include <iostream.h>
class Polygon {
protected: int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area (void) =0;
void printarea (void)
{ cout << area() << endl; }
};
class Rectangle: public Polygon {
public:
int area (void)
{ return (width * height); }
};
class Triangle: public Polygon {
public:
int area (void)
{ return (width * height / 2); }
};
int main () {
Rectangle rect;
Triangle trgl;
Polygon * p1 = &rect;
Polygon * p2 = &trgl;
p1->set_values (4,5);
p2->set_values (4,5);
p1->printarea();
p2->printarea();
return 0;
}
20
10

Más contenido relacionado

La actualidad más candente (18)

pointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpppointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpp
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
 
C++ concept of Polymorphism
C++ concept of  PolymorphismC++ concept of  Polymorphism
C++ concept of Polymorphism
 
3 Function Overloading
3 Function Overloading3 Function Overloading
3 Function Overloading
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
16 virtual function
16 virtual function16 virtual function
16 virtual function
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
Lecture5
Lecture5Lecture5
Lecture5
 
Inline function
Inline functionInline function
Inline function
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
C++ Training
C++ TrainingC++ Training
C++ Training
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 

Similar a Polymorphism in C++ - Runtime Polymorphism Using Virtual Functions

Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classDeepak Singh
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
2nd puc computer science chapter 8 function overloading
 2nd puc computer science chapter 8   function overloading 2nd puc computer science chapter 8   function overloading
2nd puc computer science chapter 8 function overloadingAahwini Esware gowda
 
C questions
C questionsC questions
C questionsparm112
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptishan743441
 
C++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming languageC++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming languageHariTharshiniBscIT1
 
Virtual function
Virtual functionVirtual function
Virtual functionzindadili
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answerssheibansari
 
CAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptxCAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptxSurajgroupsvideo
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptxhara69
 
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
 
polymorphism.pdf
polymorphism.pdfpolymorphism.pdf
polymorphism.pdfriyawagh2
 
chapter-8-function-overloading.pdf
chapter-8-function-overloading.pdfchapter-8-function-overloading.pdf
chapter-8-function-overloading.pdfstudy material
 

Similar a Polymorphism in C++ - Runtime Polymorphism Using Virtual Functions (20)

Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-class
 
Bc0037
Bc0037Bc0037
Bc0037
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
2nd puc computer science chapter 8 function overloading
 2nd puc computer science chapter 8   function overloading 2nd puc computer science chapter 8   function overloading
2nd puc computer science chapter 8 function overloading
 
C questions
C questionsC questions
C questions
 
UNIT IV (1).ppt
UNIT IV (1).pptUNIT IV (1).ppt
UNIT IV (1).ppt
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
 
C++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming languageC++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming language
 
Unit iv
Unit ivUnit iv
Unit iv
 
Virtual function
Virtual functionVirtual function
Virtual function
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Lecture6.ppt
Lecture6.pptLecture6.ppt
Lecture6.ppt
 
CAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptxCAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptx
 
Constructor
ConstructorConstructor
Constructor
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 
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
 
polymorphism.pdf
polymorphism.pdfpolymorphism.pdf
polymorphism.pdf
 
chapter-8-function-overloading.pdf
chapter-8-function-overloading.pdfchapter-8-function-overloading.pdf
chapter-8-function-overloading.pdf
 

Último

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 

Último (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 

Polymorphism in C++ - Runtime Polymorphism Using Virtual Functions

  • 1. 1 Polymorphism • It simply means ‘one name, multiple forms’. • We have already seen how the concepts of polymorphism implemented using overloaded function. • The overloaded member function are selected for invoking by matching arguments. • This information is known to the compiler at compile time and it is known as early binding . Also known as compile time polymorphism.
  • 2. #include <iostream.h> class A { public : float sum() { return 10; } float sum(float i, float j,float k) { return i+j+k; } }; class B : public A { public: using A::sum; float sum(float i) { return i; } float sum(float i, int j) { return i+j; } }; void main() { B calculate; cout<<calculate.sum(25.5)<<endl; cout<<calculate.sum(4.5,5)<<endl; cout<<calculate.sum(4.5,3.5,2.5)<<endl; cout<<calculate.sum()<<endl; } Output 25.5 9.5 10.5 10
  • 3. 3 • Consider the situation where the function name and prototype is same in both the base and derived classes. class A { int x; public: void show(){…..} }; class B : public A { public: void show(){…..} }; • Since the prototype is same, function is not overloaded. • Virtual function and pointer are used to invoke appropriate member function while the program is running and it is known as late binding . • Also known as runtime polymorphism.
  • 4. ‫وائل‬ ‫قصاص‬ 4 // pointers to base class #include <iostream.h> class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } }; class CRectangle : public CPolygon { public: int area (void){ return (width * height); } }; class CTriangle: public CPolygon { public: int area (void){ return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; CPolygon * p1 = &rect; CPolygon * p2 = &trgl; p1->set_values (4,5); p2->set_values (4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0;} 20 10 Code
  • 5. • The function main creates two pointers that point to objects of class CPolygon, that are *p1 and *p2. These are assigned to the addresses of rect and trgl, and because they are objects of classes derived from CPolygon they are valid assignations. • The only limitation of using *p1 and *p2 instead of rect and trgl is that both *p1 and *p2 are of type CPolygon* and therefore we can only refer to the members that CRectangle and CTriangle inherit from CPolygon. For that reason when calling the area() members we have not been able to use the pointers *p1 and *p2. • To make it possible for the pointers to class CPolygon to admit area () as a valid member, this should also have been declared in the base class and not only in its derived ones.
  • 6. 6 Virtual members • In order to declare an element of a class which we are going to redefine in derived classes we must precede it with the keyword virtual so that the use of pointers to objects of that class can be suitable.
  • 7. ‫وائل‬ ‫قصاص‬ 7 #include <iostream.h> class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) { return (0); } }; class CRectangle: public CPolygon { public: int area (void){ return (width * height); } }; class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; CPolygon poly; CPolygon * p1 = &rect; CPolygon *p2=&trgl; CPolygon * p3 = &poly; p1->set_values(4,5); p2->set_values(4,5); p3->set_values (4,5); cout << p1->area() << endl; cout << p2->area() << endl; cout << p3->area() << endl;} 20 10 0
  • 8. • The three classes (CPolygon, CRectangle and CTriangle) have the same members: width, height, set_values() and area(). • area() has been defined as virtual because it is later redefined in derived classes. You can verify if you want that if you remove this word (virtual) from the code and then you execute the program the result will be 0 for the three polygons instead of 20,10,0. That is because instead of calling the corresponding area() function for each object (CRectangle::area(), CTriangle::area() and CPolygon::area(), respectively), CPolygon::area() will be called for all of them since the calls are via a pointer to CPolygon. • Therefore, what the word virtual does is to allow a member of a derived class with the same name as one in the base class be suitably called when a pointer to it is used
  • 9. Abstract base classes • Abstract classes are similar to the class CPolygon of our previous example. The only difference is that in our previous example we have defined a valid area() function for objects that were of class CPolygon (like object poly), whereas in an abstract base class we could have simply left without defining this function by appending = 0 to the function declaration. • The class CPolygon could have been thus: // abstract class CPolygonclass CPolygon { protected: int width, height; public: void set_values(int a, int b){ width=a; height=b; } virtual int area (void) = 0; };
  • 10. • This type of function is called a pure virtual function, and all classes that contain a pure virtual function (do-nothing function) are considered abstract base classes. • The greatest difference of an abstract base class is that instances (objects) of it cannot be created, but we can create pointers to them. Therefore a declaration likes: CPolygon poly; // incorrect CPolygon * ppoly1; //correct • This is because the pure virtual function that it includes is not defined and it is impossible to create an object if it does not have all its members defined. A pointer that points to an object of a derived class where this function has been defined is perfectly valid. • The main objective of an abstract base class is to provide some traits to the derived classes and to create a base pointer required for achieving run time polymorphism.
  • 11. #include <iostream.h> class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) = 0; }; class CRectangle: public CPolygon { public: int area (void) {return (width * height); } }; class CTriangle: public CPolygon { public: int area (void) {return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout << ppoly1->area() << endl; cout << ppoly2->area() << endl; return 0; } 20 10
  • 12. ‫وائل‬ ‫قصاص‬ 12 #include <iostream.h> class Polygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; void printarea (void) { cout << area() << endl; } }; class Rectangle: public Polygon { public: int area (void) { return (width * height); } }; class Triangle: public Polygon { public: int area (void) { return (width * height / 2); } }; int main () { Rectangle rect; Triangle trgl; Polygon * p1 = &rect; Polygon * p2 = &trgl; p1->set_values (4,5); p2->set_values (4,5); p1->printarea(); p2->printarea(); return 0; } 20 10