SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (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
gourav kottawar
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
Rajab Ali
 
C++ concept of Polymorphism
C++ concept of  PolymorphismC++ concept of  Polymorphism
C++ concept of Polymorphism
kiran Patel
 
3 Function Overloading
3 Function Overloading3 Function Overloading
3 Function Overloading
Praveen M Jigajinni
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
Sangharsh agarwal
 
Virtual function
Virtual functionVirtual function
Virtual function
harman kaur
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)
Faizan Janjua
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
Envision Computer Training Institute
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
Himanshu Kaushik
 
16 virtual function
16 virtual function16 virtual function
16 virtual function
Docent Education
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
temkin abdlkader
 
Lecture5
Lecture5Lecture5
Lecture5
ravifeelings
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Sikder Tahsin Al-Amin
 
C++ Training
C++ TrainingC++ Training
C++ Training
SubhendraBasu5
 
Function overloading
Function overloadingFunction overloading
Function overloading
Selvin Josy Bai Somu
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
Geeks Anonymes
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Pranali Chaudhari
 

Similar to Polymorphismupload (20)

Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-class
Deepak Singh
 
polymorphism for b.tech iii year students
polymorphism for b.tech iii year studentspolymorphism for b.tech iii year students
polymorphism for b.tech iii year students
Somesh Kumar
 
Bc0037
Bc0037Bc0037
Bc0037
hayerpa
 
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 overloading
Aahwini Esware gowda
 
C questions
C questionsC questions
C questions
parm112
 
UNIT IV (1).ppt
UNIT IV (1).pptUNIT IV (1).ppt
UNIT IV (1).ppt
VGaneshKarthikeyan
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
ishan743441
 
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
HariTharshiniBscIT1
 
Unit iv
Unit ivUnit iv
Unit iv
snehaarao19
 
Virtual function
Virtual functionVirtual function
Virtual function
zindadili
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
sheibansari
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
1HK19CS090MOHAMMEDSA
 
Polymorphism in C++ for beginners reference
Polymorphism  in C++ for beginners referencePolymorphism  in C++ for beginners reference
Polymorphism in C++ for beginners reference
21pd23
 
Lecture6.ppt
Lecture6.pptLecture6.ppt
Lecture6.ppt
ammu241754
 
CAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptxCAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptx
Surajgroupsvideo
 
Constructor
ConstructorConstructor
Constructor
abhay singh
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
hara69
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
Kaushik Raghupathi
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-class
Deepak Singh
 
polymorphism for b.tech iii year students
polymorphism for b.tech iii year studentspolymorphism for b.tech iii year students
polymorphism for b.tech iii year students
Somesh Kumar
 
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 overloading
Aahwini Esware gowda
 
C questions
C questionsC questions
C questions
parm112
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
ishan743441
 
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
HariTharshiniBscIT1
 
Virtual function
Virtual functionVirtual function
Virtual function
zindadili
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
sheibansari
 
Polymorphism in C++ for beginners reference
Polymorphism  in C++ for beginners referencePolymorphism  in C++ for beginners reference
Polymorphism in C++ for beginners reference
21pd23
 
CAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptxCAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptx
Surajgroupsvideo
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
hara69
 
Ad

Recently uploaded (20)

Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Ad

Polymorphismupload

  • 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