SlideShare une entreprise Scribd logo
1  sur  12
Lecture 21



Virtual Functions
Introduction:
               Overloading vs. Overriding


• Overloading is a form of polymorphism which means
  that a program construct which has a certain
  appearance can mean different things (for example, calls
  to different functions) depending on the types of the
  parameters involved.    Example

• Overriding is also a form of polymorphism which means
  that a derived class defines a function that has similar
  name and no. & types of parameters as its base class
  but the implementation of both functions are different.
                           Example
Overloading

Patient:
 Data Member:
       IdNumber, PatName
 Function member:
       SetDetails(int , char)



Inpatient:
 Data Member:
       Wardnumber, Daysinward
 Function member:
       SetDetails(int, char, int, int)
       // overload function member
Overriding

Patient:
 Data Member:
       IdNumber, PatName
 Function member:
       DisplayDetails() { cout<<IdNumber<<PatNumber; }



Inpatient:
 Data Member:
       Wardnumber, Daysinward
 Function member:
       DisplayDetails() {cout<<Wardnumber<<Daysinward;}
       // override function member
Introduction
• Binding means deciding exactly which form or function
  is appropriate.
• Binding occurs during
   • during compilation is called static or early binding,
   • during program execution is called dynamic or late
     binding.
                                 Dynamic Binding
 Static Binding                  In C++, to implement dynamic
 Usually is known ad hoc         binding, use virtual functions.
 polymorphism.
                                 A member function is declared
                                 as virtual by writing the word
 Performed at compile-time       virtual first in the
 when a function is called via   declaration.
 a specific object or via a
 pointer to an object            Syntax:
                                     virtual return_type
                                     function_name (arg_list….)
Static Binding : Sample Program

#include <iostream.h>                              void Displaydetails()
                                                      { cout<<endl<<"Inpatient:"<<IdNumber<<
class Patient {                                         Wardnumber<<Daysinward; }
public:                                            };
    int IdNumber; char Name;
   void Setdetails (int I, char N)                 void main()
   { IdNumber = I; Name = N;             }         { Patient p1;
   void Displaydetails()                                 p1.Setdetails(111,'a');     // static binding
   { cout<<endl<<"Patient:"<<IdNumber                    p1.Displaydetails();       // static binding
       <<Name; } }; // end class Patient

class InPatient : public Patient {                     InPatient p2;
private: int Wardnumber;                                 p2.Setdetails(333,'z',12,14); // static binding
              int Daysinward;                            p2.Displaydetails(); // static binding
public:                                            }
   void Setdetails (int I, char N, int W, int D)
   { IdNumber = I; Name = N;
       Wardnumber = W;
       Daysinward = D;              }
Points on Dynamic Binding
•   A virtual function tells the compiler to create a pointer to a function
    but not to fill in the value of the pointer until the function is actually
    called
•   A class which contains at least one virtual function, or which
    inherits a virtual function,     is called a
                               polymorphic class.


class Shape                              class Shape
{ private: ……                            { protected: ……
   public: virtual void display()           public: virtual void display()
      { ……..}                                  { ……..}
 :                                          :
 :                                          :
};                                       };
                                         class Rectangle: public Shape
                                         { ………… };
Dynamic Binding : Sample Program 1

#include <iostream.h>                                   void Displaydetails()
                                                        { cout<<"Inpatient No: "<<IdNumber<<endl;
class Patient {                                           cout<<“ Name: “<<Name<<endl;
protected:                                                cout<<“Ward No: “<<Wardnumber<<endl;
           int IdNumber; char PatName;                    cout<<“Days: ”<< Daysinward<<endl;};
public:                                            };
   void Setdetails (int I, char N)
  {……..}                                           void main()
                                                   {         Patient *Pat1, Pat2;
   virtual void Displaydetails()                             Pat2.Setdetails(999, ’A');
  { cout<<"Patient No: "<<IdNumber<<endl;                    Pat1 = &Pat2;
   cout<< ”Name: “<<PatName<<endl; }                         Pat1 -> Displaydetails();
};                                                                     //dynamic binding

class InPatient : public Patient {                             InPatient InPat;
private:                                                       InPat.Setdetails(333, ’Z', 12, 14);
   int Wardnumber;       int Daysinward;                       Pat1 = &InPat;
public:                                                        Pat1 -> Displaydetails();
   void Setdetails (int I, char N, int W, int D)                         //dynamic binding
   { …….. }                                        }
Dynamic Binding : Sample Program 2

#include <iostream.h>                              class Professor : public Person {
#include <string.h>                                private:
class Person {                                                 int publs;
protected:                                         public:
            char *name;                                 Professor (char* s, int n) : Person(s), publs(n) {}
public:                                                 void print() { cout<<"My name is "<<name
   Person(char *s) {………..}                              << " and I have "<<
   virtual void print() {                          publs<<"publications."; }
      cout<<"My name is "<<name<< ".n"; }         }; // End class Professor
}; // End class Person                             void main()
                                                   { Person* P;
class Student : public Person {                          Person P2("Ali");
private:                                                 Student Stud1("Fitri", 3.56);
           double gpa;                                   Professor Prof1("Halizah", 5);
public:                                                        P = &P2;           P->print();
  Student (char* s, double g) : Person(s) {….. }                                        //dynamic binding
                                                               P = &Stud1; P->print();
  void print() { cout<<"My name is "<<name                                              //dynamic binding
  << " and my G.P.A. is "<< gpa<<".n"; }                      P = &Prof1;         P->print();
}; //End class Student                                                                  //dynamic binding
                                                   } // End main block
Virtual Functions

• Once a function is declared virtual, it remains virtual all
  the way down the inheritance hierarchy when a class
  overrides it.         All display() are virtual except display()
         Person                              Person
              - virtual display()                 - display()

        Lecturer                            Lecturer
             - display()                         - virtual display()

Full Time         Part Time         Full Time        Part Time
- display()       - display()       - display()      - display()

All display() are virtual
Virtual Functions

• When a derived class chooses not to define a virtual
  function, the derived class simply inherits its immediate
  base class's virtual function definition.

           Person                     Class Lecturer inherits the
                - virtual display()   virtual function display() from
                                      class Person.
          Lecturer
               - setvalue()

  Full Time        Part Time
  - getvalue()     - getvalue()
Virtual Functions: When it is useful?


                                 Shape
                          virtual void draw();




     Circle          Triangle       Rectangle      Square
     void draw();    void draw();   void draw();   void draw();



• Each sub-class has its different definition of draw() function.
• Declare the draw() function in class Shape as virtual function.
• Each sub-class overrides the virtual function.

Contenu connexe

Tendances

Brief Summary Of C++
Brief Summary Of C++Brief Summary Of C++
Brief Summary Of C++Haris Lye
 
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHave Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHoward Lewis Ship
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable codeGeshan Manandhar
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code SmellsMario Sangiorgio
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Decaf language specification
Decaf language specificationDecaf language specification
Decaf language specificationSami Said
 
Introduction to classes the concept of a class/tutorialoutlet
Introduction to classes the concept of a class/tutorialoutletIntroduction to classes the concept of a class/tutorialoutlet
Introduction to classes the concept of a class/tutorialoutletOldingz
 
Clean code - Agile Software Craftsmanship
Clean code - Agile Software CraftsmanshipClean code - Agile Software Craftsmanship
Clean code - Agile Software CraftsmanshipYukti Kaura
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Railselliando dias
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Heiko Behrens
 
03 - Qt UI Development
03 - Qt UI Development03 - Qt UI Development
03 - Qt UI DevelopmentAndreas Jakl
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchMatteo Battaglio
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyMobileAcademy
 

Tendances (19)

Brief Summary Of C++
Brief Summary Of C++Brief Summary Of C++
Brief Summary Of C++
 
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHave Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Devoxx 2012 (v2)
Devoxx 2012 (v2)Devoxx 2012 (v2)
Devoxx 2012 (v2)
 
Decaf language specification
Decaf language specificationDecaf language specification
Decaf language specification
 
Introduction to classes the concept of a class/tutorialoutlet
Introduction to classes the concept of a class/tutorialoutletIntroduction to classes the concept of a class/tutorialoutlet
Introduction to classes the concept of a class/tutorialoutlet
 
Clean code - Agile Software Craftsmanship
Clean code - Agile Software CraftsmanshipClean code - Agile Software Craftsmanship
Clean code - Agile Software Craftsmanship
 
Eclipse Banking Day
Eclipse Banking DayEclipse Banking Day
Eclipse Banking Day
 
Clean code
Clean codeClean code
Clean code
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
The Xtext Grammar Language
The Xtext Grammar LanguageThe Xtext Grammar Language
The Xtext Grammar Language
 
Test Engine
Test EngineTest Engine
Test Engine
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009
 
Clean code
Clean codeClean code
Clean code
 
03 - Qt UI Development
03 - Qt UI Development03 - Qt UI Development
03 - Qt UI Development
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
 

En vedette (8)

Lecture20
Lecture20Lecture20
Lecture20
 
Springwood at music resonate
Springwood at music resonateSpringwood at music resonate
Springwood at music resonate
 
Lecture10
Lecture10Lecture10
Lecture10
 
Lecture16
Lecture16Lecture16
Lecture16
 
Facebook經營觀察 0820
Facebook經營觀察 0820Facebook經營觀察 0820
Facebook經營觀察 0820
 
Lecture09
Lecture09Lecture09
Lecture09
 
Lecture17
Lecture17Lecture17
Lecture17
 
Lecture05
Lecture05Lecture05
Lecture05
 

Similaire à Lecture21

Lec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsLec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsPrincess Sam
 
Virtual function
Virtual functionVirtual function
Virtual functionharman kaur
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and ObjectsPayel Guria
 
Lec 45.46- virtual.functions
Lec 45.46- virtual.functionsLec 45.46- virtual.functions
Lec 45.46- virtual.functionsPrincess Sam
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Abu Saleh
 
Inheritance in C++.ppt
Inheritance in C++.pptInheritance in C++.ppt
Inheritance in C++.pptinstaface
 
polymorpisum-140106223024-phpapp01.pdf
polymorpisum-140106223024-phpapp01.pdfpolymorpisum-140106223024-phpapp01.pdf
polymorpisum-140106223024-phpapp01.pdfBapanKar2
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1Teksify
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в JavaDEVTYPE
 
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo....NET Conf UY
 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2Aadil Ansari
 
Dart London hackathon
Dart  London hackathonDart  London hackathon
Dart London hackathonchrisbuckett
 

Similaire à Lecture21 (20)

Lecture18
Lecture18Lecture18
Lecture18
 
Lec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsLec 42.43 - virtual.functions
Lec 42.43 - virtual.functions
 
Virtual function
Virtual functionVirtual function
Virtual function
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and Objects
 
OOPS 22-23 (1).pptx
OOPS 22-23 (1).pptxOOPS 22-23 (1).pptx
OOPS 22-23 (1).pptx
 
Lec 45.46- virtual.functions
Lec 45.46- virtual.functionsLec 45.46- virtual.functions
Lec 45.46- virtual.functions
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)
 
Test Engine
Test EngineTest Engine
Test Engine
 
Inheritance in C++.ppt
Inheritance in C++.pptInheritance in C++.ppt
Inheritance in C++.ppt
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
polymorpisum-140106223024-phpapp01.pdf
polymorpisum-140106223024-phpapp01.pdfpolymorpisum-140106223024-phpapp01.pdf
polymorpisum-140106223024-phpapp01.pdf
 
Mattbrenner
MattbrennerMattbrenner
Mattbrenner
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
 
Object oriented programming 2
Object oriented programming 2Object oriented programming 2
Object oriented programming 2
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++
 
Dart London hackathon
Dart  London hackathonDart  London hackathon
Dart London hackathon
 

Dernier

Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
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
 
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
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 
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
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
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
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
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
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 

Dernier (20)

Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
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
 
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)
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 
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
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
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
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
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
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
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
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 

Lecture21

  • 2. Introduction: Overloading vs. Overriding • Overloading is a form of polymorphism which means that a program construct which has a certain appearance can mean different things (for example, calls to different functions) depending on the types of the parameters involved. Example • Overriding is also a form of polymorphism which means that a derived class defines a function that has similar name and no. & types of parameters as its base class but the implementation of both functions are different. Example
  • 3. Overloading Patient: Data Member: IdNumber, PatName Function member: SetDetails(int , char) Inpatient: Data Member: Wardnumber, Daysinward Function member: SetDetails(int, char, int, int) // overload function member
  • 4. Overriding Patient: Data Member: IdNumber, PatName Function member: DisplayDetails() { cout<<IdNumber<<PatNumber; } Inpatient: Data Member: Wardnumber, Daysinward Function member: DisplayDetails() {cout<<Wardnumber<<Daysinward;} // override function member
  • 5. Introduction • Binding means deciding exactly which form or function is appropriate. • Binding occurs during • during compilation is called static or early binding, • during program execution is called dynamic or late binding. Dynamic Binding Static Binding In C++, to implement dynamic Usually is known ad hoc binding, use virtual functions. polymorphism. A member function is declared as virtual by writing the word Performed at compile-time virtual first in the when a function is called via declaration. a specific object or via a pointer to an object Syntax: virtual return_type function_name (arg_list….)
  • 6. Static Binding : Sample Program #include <iostream.h> void Displaydetails() { cout<<endl<<"Inpatient:"<<IdNumber<< class Patient { Wardnumber<<Daysinward; } public: }; int IdNumber; char Name; void Setdetails (int I, char N) void main() { IdNumber = I; Name = N; } { Patient p1; void Displaydetails() p1.Setdetails(111,'a'); // static binding { cout<<endl<<"Patient:"<<IdNumber p1.Displaydetails(); // static binding <<Name; } }; // end class Patient class InPatient : public Patient { InPatient p2; private: int Wardnumber; p2.Setdetails(333,'z',12,14); // static binding int Daysinward; p2.Displaydetails(); // static binding public: } void Setdetails (int I, char N, int W, int D) { IdNumber = I; Name = N; Wardnumber = W; Daysinward = D; }
  • 7. Points on Dynamic Binding • A virtual function tells the compiler to create a pointer to a function but not to fill in the value of the pointer until the function is actually called • A class which contains at least one virtual function, or which inherits a virtual function, is called a polymorphic class. class Shape class Shape { private: …… { protected: …… public: virtual void display() public: virtual void display() { ……..} { ……..} : : : : }; }; class Rectangle: public Shape { ………… };
  • 8. Dynamic Binding : Sample Program 1 #include <iostream.h> void Displaydetails() { cout<<"Inpatient No: "<<IdNumber<<endl; class Patient { cout<<“ Name: “<<Name<<endl; protected: cout<<“Ward No: “<<Wardnumber<<endl; int IdNumber; char PatName; cout<<“Days: ”<< Daysinward<<endl;}; public: }; void Setdetails (int I, char N) {……..} void main() { Patient *Pat1, Pat2; virtual void Displaydetails() Pat2.Setdetails(999, ’A'); { cout<<"Patient No: "<<IdNumber<<endl; Pat1 = &Pat2; cout<< ”Name: “<<PatName<<endl; } Pat1 -> Displaydetails(); }; //dynamic binding class InPatient : public Patient { InPatient InPat; private: InPat.Setdetails(333, ’Z', 12, 14); int Wardnumber; int Daysinward; Pat1 = &InPat; public: Pat1 -> Displaydetails(); void Setdetails (int I, char N, int W, int D) //dynamic binding { …….. } }
  • 9. Dynamic Binding : Sample Program 2 #include <iostream.h> class Professor : public Person { #include <string.h> private: class Person { int publs; protected: public: char *name; Professor (char* s, int n) : Person(s), publs(n) {} public: void print() { cout<<"My name is "<<name Person(char *s) {………..} << " and I have "<< virtual void print() { publs<<"publications."; } cout<<"My name is "<<name<< ".n"; } }; // End class Professor }; // End class Person void main() { Person* P; class Student : public Person { Person P2("Ali"); private: Student Stud1("Fitri", 3.56); double gpa; Professor Prof1("Halizah", 5); public: P = &P2; P->print(); Student (char* s, double g) : Person(s) {….. } //dynamic binding P = &Stud1; P->print(); void print() { cout<<"My name is "<<name //dynamic binding << " and my G.P.A. is "<< gpa<<".n"; } P = &Prof1; P->print(); }; //End class Student //dynamic binding } // End main block
  • 10. Virtual Functions • Once a function is declared virtual, it remains virtual all the way down the inheritance hierarchy when a class overrides it. All display() are virtual except display() Person Person - virtual display() - display() Lecturer Lecturer - display() - virtual display() Full Time Part Time Full Time Part Time - display() - display() - display() - display() All display() are virtual
  • 11. Virtual Functions • When a derived class chooses not to define a virtual function, the derived class simply inherits its immediate base class's virtual function definition. Person Class Lecturer inherits the - virtual display() virtual function display() from class Person. Lecturer - setvalue() Full Time Part Time - getvalue() - getvalue()
  • 12. Virtual Functions: When it is useful? Shape virtual void draw(); Circle Triangle Rectangle Square void draw(); void draw(); void draw(); void draw(); • Each sub-class has its different definition of draw() function. • Declare the draw() function in class Shape as virtual function. • Each sub-class overrides the virtual function.