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

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
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrency
xu liwei
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_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
 
Seminar on polymorphism
Seminar on polymorphismSeminar on polymorphism
Seminar on polymorphism
023henil
 
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
 

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

More on Classes and Objects
More on Classes and ObjectsMore on Classes and Objects
More on Classes and Objects
Payel Guria
 
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
 
Lec 45.46- virtual.functions
Lec 45.46- virtual.functionsLec 45.46- virtual.functions
Lec 45.46- virtual.functions
Princess 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.pdf
arjuncorner565
 
ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6 1
ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6  1ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6  1
ฟังก์ชั่นย่อยและโปรแกรมมาตรฐาน ม. 6 1
Little 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

Visual Studio 2008 Overview
Visual Studio 2008 OverviewVisual Studio 2008 Overview
Visual Studio 2008 Overview
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

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
panagenda
 

Recently uploaded (20)

Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
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...
 
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
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
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...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
"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 ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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?
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

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++