I'm studing c++ inheritance and so I propose this code:
// 08 Diamond Inheritance 02.cpp : Defines the entry point for the console application.
// I'm using Microsoft Visual Studio 2015
#include "stdafx.h"
#include <iostream>
using namespace std;
class SuperVirtual
{
public:
int sv;
SuperVirtual(int p1 = 11) : sv(p1)
{
cout << "\n SuperVirtual ctor for &" << this;
}
virtual void methodSuperVirtual_01()
{
cout << "\n Inside SuperVirtual::methodSuperVirtual_01(): sv = " << ++sv;
}
virtual void methodSuperVirtual_02()
{
cout << "\n Inside SuperVirtual::methodSuperVirtual_02(): sv = " << ++sv;
}
};
//----------------------------------
class DerivedSV_01 : public SuperVirtual
{
public:
int dsv;
DerivedSV_01(int p1 = 21) : dsv(p1)
{
cout << "\n DerivedSV_01 ctor for &" << this;
}
virtual void methodSuperVirtual_01() override
{
cout << "\n Inside DerivedSV_01::methodSuperVirtual_01()";
}
//----------------------------------------------------
virtual void onlyForDerivedSV_01()
{
cout << "\n Inside DerivedSV_01::onlyForDerivedSV_01()";
}
};
int main()
{
SuperVirtual sv1(1);
sv1.methodSuperVirtual_01();
DerivedSV_01 dsv_01;
dsv_01.methodSuperVirtual_01();
dsv_01.onlyForDerivedSV_01();
return 0;
}
Now the question (excuse my bad english):
I had read that:
Whenever a class itself contains virtual functions or overrides virtual functions from a parent class the compiler builds a vtable for that class. The vtable contains function pointers that point to the virtual functions in that class. There can only be one vtable per class, and all objects of the same class will share the same vtable
At this point I supposed that the virtual table of class SuperVirtual contains 2 elements, while the virtual table for class DerivedSV_01 contains 3 elements: 2 for inherited (and eventually ovverridden) methods + 1 for the new virtual method '.onlyForDerivedSV_01()'.
However inspecting the objects created in the main() with the Visual Studio Debugger I found that:
- virtual table for instance of class SuperVirtual contains 2 elements (OK !)
- virtual table for instance of class DerivedSV_01 contains 2 elements (KO !!! Why ?)
For completeness of information I provide the following screenshot:
Thanks for your time.

Aucun commentaire:
Enregistrer un commentaire