SlideShare a Scribd company logo
1 of 10
Download to read offline
Virtual Functions


   By Roman Okolovich
ISO/IEC 14882:1998(E). International Standard.
First Edition 1998-09-01
   10.3 Virtual Functions
       10.3.1 Virtual Functions support dynamic binding and object-
        oriented programming. A class that declares or inherits a virtual
        function is called a polymorphic class.
       If a virtual member function vf is declared in a class Base and in a
        class Derived, derived directly or indirectly from Base, a member
        function vf with the same name and same parameter list as Base::vf
        is declared, then Derived::vf is also virtual (whether or not it is so
        declared) and it overrides Base::vf. For convenience we say that
        any virtual function overrides itself.

   C++ standard does not say anything about implementation of
    virtual functions. The compilers are free to implement it by
    any (correct) mechanism. However, practically majority of the
    compilers that exist today implement virtual functions using
    vtable mechanism.
Example
class Transaction                              // base class for all transactions
{
public:
    Transaction();
    virtual void logTransaction() const = 0;   // make type-dependent log entry
    //...
};
Transaction::Transaction()                     // implementation of base class constructor
{
    //...
    logTransaction();                          // as final action, log this transaction
}
class BuyTransaction : public Transaction      // derived class
{
public:
    virtual void logTransaction() const;       // how to log transactions of this type
    //...
};
class SellTransaction : public Transaction     // derived class
{
public:
    virtual void logTransaction() const;       // how to log transactions of this type
    //...
};
BuyTransaction b;
General classes
class A                        at the code generation
{                                level:
   int foo();                  struct D
                               {
  int a1;                        int a1;
  int a2;                        int a2;
  int a3;
                                 int a3;
};                               int b1;
class B                          int b2;
{                                int b3;
   int bar();                    int d1;
                                 int d2;
  int b1;                        int d3;
  int b2;                      };
  int b3;                      ?foo@A@@ModuleA@(A* pThis);
};                             ?bar@B@@ModuleB@(B* pThis);
class D : public A, public B   ?foo@D@@ModuleD@(D* pThis);
{
   int foo();                  D::D() {}
  int d1;
  int d2;                      A::foo( (A*)&D );
  int d3;
};
A* pA = new D;
pA->foo();
Virtual Functions
class Vbase                  at the code generation level:
                             struct Vbase
{                            {                                      static struct VbTable
     virtual void foo();        void* m_pVptr; //                  {
     virtual void bar();        int a1;                               void (*foo)();
                             };
     int a1;                 ?foo@Vbase@@ModuleVb@(Vbase* pThis);     void (*bar)();
                             ?bar@Vbase@@ModuleVb@(Vbase* pThis);   };
};
                             cBase.m_pVptr[foo_idx](&cBase);

Vbase cBase;                 struct V
                             {
cBase.foo();                    void* m_pVptr; //                  static   struct VTable
                                int a1;                             {
                                int b1;                               void   (*foo)();
                             };                                       void   (*bar)();
class V : public Vbase                                                void   (*dir)();
                             ?foo@V@@ModuleV@(V* pThis);              void   (*alpha)();
{                            ?dir@V@@ModuleV@(V* pThis);
                             ?alpha@V@@ModuleV@(V* pThis);          };
     void foo();
     virtual void dir();
     virtual void alpha();
     int b1;
};
Class Constructors
class Vbase                 at the code generation level:
{                           Vbase::Vbase
  virtual void foo();       {
  virtual void bar();         m_pVptr->[0] = void(*foo)();
  virtual void dir() = 0;     m_pVptr->[1] = void(*bar)();
     void do()                m_pVptr->[2] = 0;
     {                      };
       foo();
     }
     int a1;                V::V : Vbase()
                            {
};                            m_pVptr->[0]   =   void(*foo)();
                              m_pVptr->[1]   =   void(*Vbase::bar)();
                              m_pVptr->[2]   =   void(*dir)();
class V : public Vbase        m_pVptr->[3]   =   void(*alpha)();
{
                                Vbase::m_pVptr = m_pVptr;
   void foo();              }
   virtual void dir();
   virtual void alpha();    V objV;
   int b1;                  objV.do(Vbase* this)
};                          {
                              this->foo(); // this  Vbase
                              // foo(this);
                            }
__declspec(novtable)
class __declspec(novtable) IBase               at the code generation level:
{
   virtual void foo() = 0;                     IBase::IBase
   virtual void bar() = 0;                     {
   virtual void dir() = 0;
                                                 //m_pVptr
};                                               // will not be initialized at all
class V : public IBase                         };
{
   void foo();
   virtual void bar();
   virtual void dir();
   int b1;
};

class __declspec(novtable) A
{
public:
     A() {};
     virtual void func1(){ std::cout << 1; }
     virtual void func2(){ std::cout << 2; }
     virtual void func3(){ std::cout << 3; }
  };
class A1 : public A
{
public:
     // no func1, func2, or func3
};
Default values
#include <iostream>                            at the code generation level:
using namespace std;
                                               struct VA
                                               {
class A {                                        void* m_pVptr;
                                               };
public:
    virtual void Foo(int n = 10) {             ?foo@A@@ModuleA@(VA* pThis, 10);
        cout << "A::Foo, n = " << n << endl;   struct VB
    }                                          {
                                                 void* m_pVptr;
};                                             };

class B : public A {                           ?foo@B@@ModuleB@(VB* pThis, 20);
public:
    virtual void Foo(int n = 20) {
        cout << "B::Foo, n = " << n << endl;   A * pa = new B();
    }                                          pa->m_pVptr[fooID]((VA*)&B, XXX);
};
                                               Answer: 10
int main() {
    A * pa = new B();
    pa->Foo();
    return 0;
}
Things to Remember
   Don't call virtual functions during construction or
    destruction, because such calls will never go to a more
    derived class than that of the currently executing
    constructor or destructor.
References
   PDF: Working draft, Standard for Programming
    Language C++

More Related Content

What's hot

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 cppgourav kottawar
 
virtual function
virtual functionvirtual function
virtual functionVENNILAV6
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphismlalithambiga kamaraj
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpen Gurukul
 
OOP in C - Before GObject (Chinese Version)
OOP in C - Before GObject (Chinese Version)OOP in C - Before GObject (Chinese Version)
OOP in C - Before GObject (Chinese Version)Kai-Feng Chou
 
OOP in C - Inherit (Chinese Version)
OOP in C - Inherit (Chinese Version)OOP in C - Inherit (Chinese Version)
OOP in C - Inherit (Chinese Version)Kai-Feng Chou
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Liju Thomas
 
Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5Ismar Silveira
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Geeks Anonymes
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract classAmit Trivedi
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 FeaturesJan Rüegg
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrencyxu liwei
 
Virtual base class
Virtual base classVirtual base class
Virtual base classTech_MX
 

What's hot (20)

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
 
virtual function
virtual functionvirtual function
virtual function
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
OOP in C - Before GObject (Chinese Version)
OOP in C - Before GObject (Chinese Version)OOP in C - Before GObject (Chinese Version)
OOP in C - Before GObject (Chinese Version)
 
OOP in C - Inherit (Chinese Version)
OOP in C - Inherit (Chinese Version)OOP in C - Inherit (Chinese Version)
OOP in C - Inherit (Chinese Version)
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++
 
Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
C++ Training
C++ TrainingC++ Training
C++ Training
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
C++11
C++11C++11
C++11
 
C++11
C++11C++11
C++11
 
C++11
C++11C++11
C++11
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrency
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
 

Viewers also liked

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)Kai-Feng Chou
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismrattaj
 
Seminar on polymorphism
Seminar on polymorphismSeminar on polymorphism
Seminar on polymorphism023henil
 
Slicing of Object-Oriented Programs
Slicing of Object-Oriented ProgramsSlicing of Object-Oriented Programs
Slicing of Object-Oriented ProgramsPraveen Penumathsa
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Sanjit Shaw
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application Tech_MX
 
Applications of stack
Applications of stackApplications of stack
Applications of stackeShikshak
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTUREArchie Jamwal
 
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...cprogrammings
 

Viewers also liked (20)

16 virtual function
16 virtual function16 virtual function
16 virtual function
 
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)
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
 
Seminar on polymorphism
Seminar on polymorphismSeminar on polymorphism
Seminar on polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Slicing of Object-Oriented Programs
Slicing of Object-Oriented ProgramsSlicing of Object-Oriented Programs
Slicing of Object-Oriented Programs
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
 
Stack a Data Structure
Stack a Data StructureStack a Data Structure
Stack a Data Structure
 
polymorphism
polymorphism polymorphism
polymorphism
 
Stack Applications
Stack ApplicationsStack Applications
Stack Applications
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application
 
Stack
StackStack
Stack
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURE
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
 

Similar to Virtual Functions

Inheritance and polymorphism
Inheritance and polymorphismInheritance and polymorphism
Inheritance and polymorphismmohamed sikander
 
Inheritance compiler support
Inheritance compiler supportInheritance compiler support
Inheritance compiler supportSyed Zaid Irshad
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and ObjectsPayel Guria
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Ismar Silveira
 
C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)Ananda Kumar HN
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)Olve Maudal
 
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13Chris Ohk
 
Elements of C++11
Elements of C++11Elements of C++11
Elements of C++11Uilian Ries
 
Lec 45.46- virtual.functions
Lec 45.46- virtual.functionsLec 45.46- virtual.functions
Lec 45.46- virtual.functionsPrincess Sam
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfarjuncorner565
 
Lecture 4: Data Types
Lecture 4: Data TypesLecture 4: Data Types
Lecture 4: Data TypesEelco Visser
 
ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6 1
ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6  1ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6  1
ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6 1Little Tukta Lita
 

Similar to Virtual Functions (20)

Inheritance and polymorphism
Inheritance and polymorphismInheritance and polymorphism
Inheritance and polymorphism
 
Inheritance compiler support
Inheritance compiler supportInheritance compiler support
Inheritance compiler support
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Oop Presentation
Oop PresentationOop Presentation
Oop Presentation
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
 
Lab3
Lab3Lab3
Lab3
 
More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and Objects
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
 
Sbaw091006
Sbaw091006Sbaw091006
Sbaw091006
 
Codejunk Ignitesd
Codejunk IgnitesdCodejunk Ignitesd
Codejunk Ignitesd
 
C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
 
Elements of C++11
Elements of C++11Elements of C++11
Elements of C++11
 
Lec 45.46- virtual.functions
Lec 45.46- virtual.functionsLec 45.46- virtual.functions
Lec 45.46- virtual.functions
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
 
Composite Pattern
Composite PatternComposite Pattern
Composite Pattern
 
Lecture 4: Data Types
Lecture 4: Data TypesLecture 4: Data Types
Lecture 4: Data Types
 
ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6 1
ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6  1ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6  1
ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6 1
 
Java byte code in practice
Java byte code in practiceJava byte code in practice
Java byte code in practice
 

More from Roman Okolovich

More from Roman Okolovich (11)

Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
C# XML documentation
C# XML documentationC# XML documentation
C# XML documentation
 
code analysis for c++
code analysis for c++code analysis for c++
code analysis for c++
 
Using QString effectively
Using QString effectivelyUsing QString effectively
Using QString effectively
 
Ram Disk
Ram DiskRam Disk
Ram Disk
 
64 bits for developers
64 bits for developers64 bits for developers
64 bits for developers
 
Visual Studio 2008 Overview
Visual Studio 2008 OverviewVisual Studio 2008 Overview
Visual Studio 2008 Overview
 
State Machine Framework
State Machine FrameworkState Machine Framework
State Machine Framework
 
The Big Three
The Big ThreeThe Big Three
The Big Three
 
Parallel Programming
Parallel ProgrammingParallel Programming
Parallel Programming
 
Smart Pointers
Smart PointersSmart Pointers
Smart Pointers
 

Recently uploaded

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 

Recently uploaded (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Virtual Functions

  • 1. Virtual Functions By Roman Okolovich
  • 2. ISO/IEC 14882:1998(E). International Standard. First Edition 1998-09-01  10.3 Virtual Functions  10.3.1 Virtual Functions support dynamic binding and object- oriented programming. A class that declares or inherits a virtual function is called a polymorphic class.  If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf. For convenience we say that any virtual function overrides itself.  C++ standard does not say anything about implementation of virtual functions. The compilers are free to implement it by any (correct) mechanism. However, practically majority of the compilers that exist today implement virtual functions using vtable mechanism.
  • 3. Example class Transaction // base class for all transactions { public: Transaction(); virtual void logTransaction() const = 0; // make type-dependent log entry //... }; Transaction::Transaction() // implementation of base class constructor { //... logTransaction(); // as final action, log this transaction } class BuyTransaction : public Transaction // derived class { public: virtual void logTransaction() const; // how to log transactions of this type //... }; class SellTransaction : public Transaction // derived class { public: virtual void logTransaction() const; // how to log transactions of this type //... }; BuyTransaction b;
  • 4. General classes class A at the code generation { level: int foo(); struct D { int a1; int a1; int a2; int a2; int a3; int a3; }; int b1; class B int b2; { int b3; int bar(); int d1; int d2; int b1; int d3; int b2; }; int b3; ?foo@A@@ModuleA@(A* pThis); }; ?bar@B@@ModuleB@(B* pThis); class D : public A, public B ?foo@D@@ModuleD@(D* pThis); { int foo(); D::D() {} int d1; int d2; A::foo( (A*)&D ); int d3; }; A* pA = new D; pA->foo();
  • 5. Virtual Functions class Vbase at the code generation level: struct Vbase { { static struct VbTable virtual void foo(); void* m_pVptr; //  { virtual void bar(); int a1; void (*foo)(); }; int a1; ?foo@Vbase@@ModuleVb@(Vbase* pThis); void (*bar)(); ?bar@Vbase@@ModuleVb@(Vbase* pThis); }; }; cBase.m_pVptr[foo_idx](&cBase); Vbase cBase; struct V { cBase.foo(); void* m_pVptr; //  static struct VTable int a1; { int b1; void (*foo)(); }; void (*bar)(); class V : public Vbase void (*dir)(); ?foo@V@@ModuleV@(V* pThis); void (*alpha)(); { ?dir@V@@ModuleV@(V* pThis); ?alpha@V@@ModuleV@(V* pThis); }; void foo(); virtual void dir(); virtual void alpha(); int b1; };
  • 6. Class Constructors class Vbase at the code generation level: { Vbase::Vbase virtual void foo(); { virtual void bar(); m_pVptr->[0] = void(*foo)(); virtual void dir() = 0; m_pVptr->[1] = void(*bar)(); void do() m_pVptr->[2] = 0; { }; foo(); } int a1; V::V : Vbase() { }; m_pVptr->[0] = void(*foo)(); m_pVptr->[1] = void(*Vbase::bar)(); m_pVptr->[2] = void(*dir)(); class V : public Vbase m_pVptr->[3] = void(*alpha)(); { Vbase::m_pVptr = m_pVptr; void foo(); } virtual void dir(); virtual void alpha(); V objV; int b1; objV.do(Vbase* this) }; { this->foo(); // this  Vbase // foo(this); }
  • 7. __declspec(novtable) class __declspec(novtable) IBase at the code generation level: { virtual void foo() = 0; IBase::IBase virtual void bar() = 0; { virtual void dir() = 0; //m_pVptr }; // will not be initialized at all class V : public IBase }; { void foo(); virtual void bar(); virtual void dir(); int b1; }; class __declspec(novtable) A { public: A() {}; virtual void func1(){ std::cout << 1; } virtual void func2(){ std::cout << 2; } virtual void func3(){ std::cout << 3; } }; class A1 : public A { public: // no func1, func2, or func3 };
  • 8. Default values #include <iostream> at the code generation level: using namespace std; struct VA { class A { void* m_pVptr; }; public: virtual void Foo(int n = 10) { ?foo@A@@ModuleA@(VA* pThis, 10); cout << "A::Foo, n = " << n << endl; struct VB } { void* m_pVptr; }; }; class B : public A { ?foo@B@@ModuleB@(VB* pThis, 20); public: virtual void Foo(int n = 20) { cout << "B::Foo, n = " << n << endl; A * pa = new B(); } pa->m_pVptr[fooID]((VA*)&B, XXX); }; Answer: 10 int main() { A * pa = new B(); pa->Foo(); return 0; }
  • 9. Things to Remember  Don't call virtual functions during construction or destruction, because such calls will never go to a more derived class than that of the currently executing constructor or destructor.
  • 10. References  PDF: Working draft, Standard for Programming Language C++