SlideShare a Scribd company logo
1 of 17
Chapter: 11


    Virtual Functions
             Lecture: 42 and 43
      Date: 23.10.2012 and 31.10.2012
Advanced C++ Topics

   Virtual functions
   Friend functions
   Static function
   Overloaded “= ” operator
   Overloaded Copy Constructor
   “this” pointer
Motivation: Virtual Functions

    a hierarchy of                                Line   draw()

    geometric shape
    classes                        Rectangle                 Circle
                                                                  draw()
    −   draws circles, ellipses,         draw()

        rectangles etc              Square                  Ellipse
                                         draw()                   draw()

    just use method
    draw throughout the
    hierarchy
Pointers to Derived Classes
   C++ allows base class pointers to point to
    derived class objects.
   Let we have
      class base { … };

      class derived : public base { … };

   Then we can write:
       base *p1;
       derived d_obj;
       p1 = &d_obj;
   class Base {                     void main()
   public:                          {
      void show() {
        cout << “basen”;           Derv1 dv1;
      }                             Derv2 dv2;
   };
   class Derv1 : public base {      Base *ptr
   public:                          ptr = &dv1;
      void show() {                 ptr->show();
        cout << “derived1n”;
      }                             ptr = &dv2;
   class Derv2 : public base {      ptr ->show();
   public:
      void show() {                 return 0;
        cout << “derived2n”;       }
      }
   };
Non-Virtual Pointer Access
   class Base {                     void main()
   public:                          {
    virtual void show() {
        cout << “basen”;           Derv1 dv1;
      }                             Derv2 dv2;
   };
   class Derv1 : public base {      Base *ptr
   public:                          ptr = &dv1;
      void show() {                 ptr->show();
        cout << “derived1n”;
      }                             ptr = &dv2;
   class Derv2 : public base {      ptr ->show();
   public:
      void show() {                 return 0;
        cout << “derived2n”;       }
      }
   };
Non-Virtual Pointer Access
Introduction to Virtual Functions
   A virtual function is a member function that is declared
    within a base class and redefined (called overriding) by a
    derived class.

   It implements the “one interface, multiple methods”
    philosophy that underlies polymorphism.

   The keyword virtual is used to designate a member
    function as virtual.

   Supports run-time polymorphism with the help of base
    class pointers.
Introduction to Virtual Functions
                  (contd.)
   While redefining a virtual function in a derived
    class, the function signature must match the original
    function present in the base class.
   So, we call it overriding, not overloading.
   When a virtual function is redefined by a derived
    class, the keyword virtual is not needed (but can be
    specified if the programmer wants).
   The “virtual”-ity of the member function continues
    along the inheritance chain.
   A class that contains a virtual function is referred to
    as a polymorphic class.
Abstract Classes and
             Pure Virtual Functions
   A base class whose objects are never instantiated is
    called an abstract class. Such a class exists only to
    act as a parent of derived classes that will be used to
    instantiate objects.
   A base class made as an abstract class must contain
    at least one pure virtual function.
   A pure virtual function is one with the expression
    “=0” added to the function declaration.
    e.g.,
         virtual void show() = 0;
   class Base {                     void main()
   public:                          {
    virtual void show() = 0;
   };                               Base bad; //ERROR

   class Derv1 : public base {      Derv1 dv1;
   public:                          Derv2 dv2;
     void show() {
       cout << “derived1n”;        Base *ptr
     }                              ptr = &dv1;
                                     ptr->show();
   class Derv2 : public base {
   public:                          ptr = &dv2;
      void show() {                 ptr ->show();
        cout << “derived2n”;
      }                             return 0;
   };                               }
Virtual Function and
                  person Class


   C++ program example, Robert Lafore, 4th ed. p.511.
Virtual Base Classes
Multiple Inheritance
Virtual Base Classes
         class Parent {
         protected:
              int basedata;
         };

         class Child1 : public parent {
           {    };

         class Child2 : public base {
           {   };

         class GrandChild:
          public Child1, public Child2
         { public:
           int getdata() { return basedata; } //ERROR
         };
Virtual Base Classes
   class Parent {                                 class Parent {
   protected:                                     protected:
         int basedata;                                  int basedata;
   };
                                                   };

                                                   class Child1 : virtual public parent {
   class Child1 : public parent {                   {      };
     {     };
                                                   class Child2 : virtual public base {
   class Child2 : public base {                     {     };
     {     };
                                                   class GrandChild:
   class GrandChild:                               public Child1, public Child2
                                                   {
    public Child1, public Child2                   public:
   {
                                                       int getdata()
   public:
         int getdata()                                      { return basedata; } //OK
               { return basedata; }   //ERROR         };
   };
Friend Functions
   Encapsulation and data-hiding dictate that
    nonmember functions should not be able to access
    an object’s private or protected data.

   Imagine you need a function to operate on objects
    of two different classes. Perhaps the function will
    take objects of the two classes as arguments, and
    operate on their private data.
     In such satiation friend functions are used…
     Precisely, a friend function is one declared outside of
      classes and still operates on their private data.

More Related Content

What's hot

Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphismlalithambiga kamaraj
 
Multiple inheritance in c++
Multiple inheritance in c++Multiple inheritance in c++
Multiple inheritance in c++Saket Pathak
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismJussi Pohjolainen
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpprajshreemuthiah
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpen Gurukul
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overviewgourav kottawar
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Geeks Anonymes
 
Virtual function
Virtual functionVirtual function
Virtual functionzindadili
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++RAJ KUMAR
 
C# for-java-developers
C# for-java-developersC# for-java-developers
C# for-java-developersDhaval Dalal
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answerssheibansari
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementSreedhar Chowdam
 

What's hot (19)

Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
Multiple inheritance in c++
Multiple inheritance in c++Multiple inheritance in c++
Multiple inheritance in c++
 
C++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphismC++: inheritance, composition, polymorphism
C++: inheritance, composition, polymorphism
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
 
Constructor,destructors cpp
Constructor,destructors cppConstructor,destructors cpp
Constructor,destructors cpp
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)
 
C++ presentation
C++ presentationC++ presentation
C++ presentation
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
Virtual function
Virtual functionVirtual function
Virtual function
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
C# for-java-developers
C# for-java-developersC# for-java-developers
C# for-java-developers
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 

Viewers also liked

Viewers also liked (20)

16 virtual function
16 virtual function16 virtual function
16 virtual function
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
 
OOP in C - Virtual Function (Chinese Version)
OOP in C - Virtual Function (Chinese Version)OOP in C - Virtual Function (Chinese Version)
OOP in C - Virtual Function (Chinese Version)
 
Uid
UidUid
Uid
 
Technical knowledge sharing for undergraduates
Technical knowledge sharing for undergraduatesTechnical knowledge sharing for undergraduates
Technical knowledge sharing for undergraduates
 
Manipulators
ManipulatorsManipulators
Manipulators
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
PARAMETER PASSING MECHANISMS
PARAMETER PASSING MECHANISMSPARAMETER PASSING MECHANISMS
PARAMETER PASSING MECHANISMS
 
Lec 45.46- virtual.functions
Lec 45.46- virtual.functionsLec 45.46- virtual.functions
Lec 45.46- virtual.functions
 
Roots of polynomials
Roots of polynomialsRoots of polynomials
Roots of polynomials
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
Es272 ch3b
Es272 ch3bEs272 ch3b
Es272 ch3b
 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
 
Inheritance
InheritanceInheritance
Inheritance
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and output
 
Parm
ParmParm
Parm
 
Array and string
Array and stringArray and string
Array and string
 
Bitwise operators
Bitwise operatorsBitwise operators
Bitwise operators
 
OOP C++
OOP C++OOP C++
OOP C++
 

Similar to Lec 42.43 - virtual.functions

Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Lecture 6, c++(complete reference,herbet sheidt)chapter-16Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Lecture 6, c++(complete reference,herbet sheidt)chapter-16Abu Saleh
 
Lecture 4: Data Types
Lecture 4: Data TypesLecture 4: Data Types
Lecture 4: Data TypesEelco Visser
 
Inheritance and polymorphism
Inheritance and polymorphismInheritance and polymorphism
Inheritance and polymorphismmohamed sikander
 
Implementation of interface9 cm604.30
Implementation of interface9 cm604.30Implementation of interface9 cm604.30
Implementation of interface9 cm604.30myrajendra
 
lecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdflecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdfAneesAbbasi14
 
Dart London hackathon
Dart  London hackathonDart  London hackathon
Dart London hackathonchrisbuckett
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerGarth Gilmour
 
Chapter26 inheritance-ii
Chapter26 inheritance-iiChapter26 inheritance-ii
Chapter26 inheritance-iiDeepak Singh
 

Similar to Lec 42.43 - virtual.functions (20)

Lecture21
Lecture21Lecture21
Lecture21
 
Mattbrenner
MattbrennerMattbrenner
Mattbrenner
 
Inheritance
InheritanceInheritance
Inheritance
 
Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Lecture 6, c++(complete reference,herbet sheidt)chapter-16Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Lecture 6, c++(complete reference,herbet sheidt)chapter-16
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Lecture 4: Data Types
Lecture 4: Data TypesLecture 4: Data Types
Lecture 4: Data Types
 
Inheritance and polymorphism
Inheritance and polymorphismInheritance and polymorphism
Inheritance and polymorphism
 
OOPS IN C++
OOPS IN C++OOPS IN C++
OOPS IN C++
 
Implementation of interface9 cm604.30
Implementation of interface9 cm604.30Implementation of interface9 cm604.30
Implementation of interface9 cm604.30
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
 
lecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdflecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdf
 
Dart London hackathon
Dart  London hackathonDart  London hackathon
Dart London hackathon
 
Test Engine
Test EngineTest Engine
Test Engine
 
Test Engine
Test EngineTest Engine
Test Engine
 
inhertance c++
inhertance c++inhertance c++
inhertance c++
 
06 inheritance
06 inheritance06 inheritance
06 inheritance
 
Lecture19
Lecture19Lecture19
Lecture19
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
Chapter26 inheritance-ii
Chapter26 inheritance-iiChapter26 inheritance-ii
Chapter26 inheritance-ii
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
 

More from Princess Sam

Lec 49 - stream-files
Lec 49 - stream-filesLec 49 - stream-files
Lec 49 - stream-filesPrincess Sam
 
Lec 40.41 - pointers
Lec 40.41 -  pointersLec 40.41 -  pointers
Lec 40.41 - pointersPrincess Sam
 
Lec 38.39 - pointers
Lec 38.39 -  pointersLec 38.39 -  pointers
Lec 38.39 - pointersPrincess Sam
 
Lec 47.48 - stream-files
Lec 47.48 - stream-filesLec 47.48 - stream-files
Lec 47.48 - stream-filesPrincess Sam
 
Lec 33 - inheritance
Lec 33 -  inheritanceLec 33 -  inheritance
Lec 33 - inheritancePrincess Sam
 
Lec 30.31 - inheritance
Lec 30.31 -  inheritanceLec 30.31 -  inheritance
Lec 30.31 - inheritancePrincess Sam
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloadingPrincess Sam
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloadingPrincess Sam
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-stringsPrincess Sam
 

More from Princess Sam (12)

Lec 50
Lec 50Lec 50
Lec 50
 
Lec 49 - stream-files
Lec 49 - stream-filesLec 49 - stream-files
Lec 49 - stream-files
 
Lec 40.41 - pointers
Lec 40.41 -  pointersLec 40.41 -  pointers
Lec 40.41 - pointers
 
Lec 38.39 - pointers
Lec 38.39 -  pointersLec 38.39 -  pointers
Lec 38.39 - pointers
 
Lec 47.48 - stream-files
Lec 47.48 - stream-filesLec 47.48 - stream-files
Lec 47.48 - stream-files
 
Lec 37 - pointers
Lec 37 -  pointersLec 37 -  pointers
Lec 37 - pointers
 
Lec 33 - inheritance
Lec 33 -  inheritanceLec 33 -  inheritance
Lec 33 - inheritance
 
Lec 30.31 - inheritance
Lec 30.31 -  inheritanceLec 30.31 -  inheritance
Lec 30.31 - inheritance
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
Lec 36 - pointers
Lec 36 -  pointersLec 36 -  pointers
Lec 36 - pointers
 

Lec 42.43 - virtual.functions

  • 1. Chapter: 11 Virtual Functions Lecture: 42 and 43 Date: 23.10.2012 and 31.10.2012
  • 2. Advanced C++ Topics  Virtual functions  Friend functions  Static function  Overloaded “= ” operator  Overloaded Copy Constructor  “this” pointer
  • 3. Motivation: Virtual Functions  a hierarchy of Line draw() geometric shape classes Rectangle Circle draw() − draws circles, ellipses, draw() rectangles etc Square Ellipse draw() draw()  just use method draw throughout the hierarchy
  • 4. Pointers to Derived Classes  C++ allows base class pointers to point to derived class objects.  Let we have  class base { … };  class derived : public base { … };  Then we can write: base *p1; derived d_obj; p1 = &d_obj;
  • 5. class Base {  void main()  public:  {  void show() {  cout << “basen”;  Derv1 dv1;  }  Derv2 dv2;  };  class Derv1 : public base {  Base *ptr  public:  ptr = &dv1;  void show() {  ptr->show();  cout << “derived1n”;  }  ptr = &dv2;  class Derv2 : public base {  ptr ->show();  public:  void show() {  return 0;  cout << “derived2n”;  }  }  };
  • 7. class Base {  void main()  public:  {  virtual void show() {  cout << “basen”;  Derv1 dv1;  }  Derv2 dv2;  };  class Derv1 : public base {  Base *ptr  public:  ptr = &dv1;  void show() {  ptr->show();  cout << “derived1n”;  }  ptr = &dv2;  class Derv2 : public base {  ptr ->show();  public:  void show() {  return 0;  cout << “derived2n”;  }  }  };
  • 9. Introduction to Virtual Functions  A virtual function is a member function that is declared within a base class and redefined (called overriding) by a derived class.  It implements the “one interface, multiple methods” philosophy that underlies polymorphism.  The keyword virtual is used to designate a member function as virtual.  Supports run-time polymorphism with the help of base class pointers.
  • 10. Introduction to Virtual Functions (contd.)  While redefining a virtual function in a derived class, the function signature must match the original function present in the base class.  So, we call it overriding, not overloading.  When a virtual function is redefined by a derived class, the keyword virtual is not needed (but can be specified if the programmer wants).  The “virtual”-ity of the member function continues along the inheritance chain.  A class that contains a virtual function is referred to as a polymorphic class.
  • 11. Abstract Classes and Pure Virtual Functions  A base class whose objects are never instantiated is called an abstract class. Such a class exists only to act as a parent of derived classes that will be used to instantiate objects.  A base class made as an abstract class must contain at least one pure virtual function.  A pure virtual function is one with the expression “=0” added to the function declaration. e.g., virtual void show() = 0;
  • 12. class Base {  void main()  public:  {  virtual void show() = 0;  };  Base bad; //ERROR  class Derv1 : public base {  Derv1 dv1;  public:  Derv2 dv2;  void show() {  cout << “derived1n”;  Base *ptr  }  ptr = &dv1;  ptr->show();  class Derv2 : public base {  public:  ptr = &dv2;  void show() {  ptr ->show();  cout << “derived2n”;  }  return 0;  };  }
  • 13. Virtual Function and person Class  C++ program example, Robert Lafore, 4th ed. p.511.
  • 15. Virtual Base Classes  class Parent {  protected:  int basedata;  };  class Child1 : public parent { { };  class Child2 : public base { { };  class GrandChild: public Child1, public Child2  { public: int getdata() { return basedata; } //ERROR  };
  • 16. Virtual Base Classes  class Parent {  class Parent {  protected:  protected:  int basedata;  int basedata;  };  };  class Child1 : virtual public parent {  class Child1 : public parent { { }; { };  class Child2 : virtual public base {  class Child2 : public base { { }; { };  class GrandChild:  class GrandChild: public Child1, public Child2  { public Child1, public Child2  public:  { int getdata()  public: int getdata() { return basedata; } //OK { return basedata; } //ERROR };  };
  • 17. Friend Functions  Encapsulation and data-hiding dictate that nonmember functions should not be able to access an object’s private or protected data.  Imagine you need a function to operate on objects of two different classes. Perhaps the function will take objects of the two classes as arguments, and operate on their private data.  In such satiation friend functions are used…  Precisely, a friend function is one declared outside of classes and still operates on their private data.

Editor's Notes

  1. Student Book