Reputation: 137
Is virtual table will be created for the derived class which is not having any virtual function except parent class a virtual function which is not overridden by derived class.
for ex:
class A{
public:
virtual void show();
};
class B : public A
{
};
How about the virtual table of class B.
Upvotes: 6
Views: 1923
Reputation: 383
Here is what gdb says when compiled with g++ (Ubuntu 8.2.0-1ubuntu2~18.04) 8.2.0
15 class A
16 {
17 public:
18 virtual void show(){}
19 };
20
21 class B:public A
22 {
23 };
24
(gdb) l
25 int main()
26 {
27 A a;
28 B b;
29 }
(gdb) p a
$5 = {_vptr.A = 0x55555575f5c8 <vtable for A+16>}
(gdb) p b
$6 = {<A> = {_vptr.A = 0x55555575f5b0 <vtable for B+16>}, <No data fields>}
(gdb)
Thus, at least in this case, we can conclude that base and derived classes have distinct vtables.
Upvotes: 2
Reputation: 1092
You can check it by looking into object's contents. I wrote this simple program that prints the contents of the base class, derived class and a class that is the same as the base class but with a normal method instead of the virtual one:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Base {
public:
virtual void show() {}
};
class Derived : public Base
{ };
class NonVirtual {
public:
void show() {}
};
struct Test
{
int data1, data2;
};
template <typename T>
void showContents(T* obj, string name)
{
Test* test = new Test{};
test = reinterpret_cast<Test*>(obj);
cout << name << ": " << hex << "0x" << test->data1 << " " << "0x" << test->data2 << endl;
delete test;
}
int main()
{
Base* base = new Base{};
Derived* derived = new Derived{};
NonVirtual* nonVirtual = new NonVirtual{};
showContents(base, "Base");
showContents(derived, "Derived");
showContents(nonVirtual, "NonVirtual");
delete base;
delete derived;
delete nonVirtual;
}
The result of running the above program after compiling it with cpp.sh (I'm not sure what compiler is used there):
Base: 0x4013e0 0x0
Derived: 0x401400 0x0
NonVirtual: 0x0 0x0
so I'd expect it to mean that there has been a virtual table created for the Derived
object indeed (at least for this compiler - as required behavior is not defined in the C++ standard).
Upvotes: 0
Reputation: 2813
There is no standard answer for your question. Its really depending on the compiler version. There is no standard ABI specified in C++. If you are interested deeper please take a look at "Itanium C++ ABI" or try to find the answer on your own by looking into the asembler code.
There was even a proposal to define portable ABI for C++
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4028.pdf
Upvotes: 2