22.1.  virtual Pointers, virtual Tables

[ fromfile: vtable.xml id: vtable ]

Example 22.1. src/derivation/typeid/vtable.h

[ . . . . ]
class Base {
 protected:
    int m_X, m_Y;
 public:
    Base();
    virtual ~Base();
    virtual void virtualFun() const;
};

class Derived : public Base {
    int m_Z;
 public:
    Derived();
    ~Derived();
    void virtualFun() const ;
};
[ . . . . ]

Example 22.2. src/derivation/typeid/vtable.cpp

#include <QDebug>
#include <QString>
#include "vtable.h"

Base::Base() {
    m_X = 4;
    m_Y = 12;
    qDebug() << " Base::Base: " ;
    virtualFun();
}

Derived::Derived() {
    m_X = 5;
    m_Y = 13;
    m_Z = 22;
}

void Base::virtualFun() const {
    QString val=QString("[%1,%2]").arg(m_X).arg(m_Y);
    qDebug() << " VF: the opposite of Acid: " << val;
}

void Derived::virtualFun() const {
    QString val=QString("[%1,%2,%3]")
        .arg(m_X).arg(m_Y).arg(m_Z);
    qDebug() << " VF: add some treble: " ;
}

Base::~Base() {
    qDebug() << " ~Base() " ;
    virtualFun();
}

Derived::~Derived() {
    qDebug() << " ~Derived() " ;
}


int main() {
    Base *b = new Derived;  1 
    b->virtualFun();        2
    delete b;               3
}

1

Base::virtualFun() is called

2

calls Derived::virtualFun() using the vtable and runtime binding

3

Base::virtualFun() is called


 Base::Base:  
 VF: the opposite of Acid:  "[4,12]" 
 VF: add some treble:  
 ~Derived()  
 ~Base()  
 VF: the opposite of Acid:  "[5,13]"