与派生类的虚拟指针混淆 [英] Confusion with virtual pointer of derived class
问题描述
具有虚拟功能的Base和Derived也具有这样的虚拟功能,
Base having a virtual function and Derived also having one virtual function like this,
class Base
{
private:
int i;
public:
Base(int data = 9):i(data)
{
cout << "In Base class constructor" << endl;
}
void display()
{
cout << "In Base class" << endl;
cout << "i = " << i << endl;
}
virtual ~Base()
{
cout << "In Base class destructor" << endl;
}
};
class Derived: public Base
{
private:
int j;
public:
Derived(int data = 10):Base(11),j(data)
{
cout << "In Derived class constructor" << endl;
}
virtual void display()
{
cout << "In Derived class" << endl;
cout << "j = " << j << endl;
}
~Derived()
{
cout << "In Derived class destructor" << endl;
}
};
现在在gdb中,我看到Derived类对象的总大小为16个字节(int + int + _vptr + _vptr),但是当我在gdb中打印每个对象时,我会感到困惑,对于基类,它显示如下
Now in gdb I see the total size of the Derived class object is 16 bytes (int+int+_vptr+_vptr), but when I print each object in gdb I'm getting confused, for base class it's showing like this
$1 = {_vptr.Base = 0x401010, i = 11}
很好,但是对于派生来说,它显示的是这样的
$1 = {_vptr.Base = 0x401010, i = 11}
and it's fine, but for derived it's showing something like this
$2 = {<Base> = {_vptr.Base = 0x401010, i = 11}, j = 10}
我没有看到派生类的虚拟指针.根据我的理解,除了继承的基类虚拟指针外,派生类中还应该有一个虚拟指针指向其自己的虚拟表.我在这里做错什么了吗,还是有其他方法可以解决?
I'm not seeing the virtual pointer of the derived class. As per my understanding in addition to the base class virtual pointer which is inherited, there should be one more virtual pointer in the derived class that should point to it's own virtual table. Am I doing something wrong here or is there any other way to get it?
推荐答案
派生类具有自己的vtable
.因此,该类型的对象只有一个指向它的指针.该vtable
包含指向Base
成员函数的条目,如果它们没有被覆盖的话.因此,在类型为Derived
的对象中不需要指向Base
的vtable的指针.
The derived class has its own vtable
. So objects of that type have a single pointer to it. That vtable
contains entries that point to Base
s member functions if they aren't overridden. So there is no need for a pointer to Base
s vtable in objects of type Derived
.
在Derived
中出现_vptr.Base
的原因是因为您没有覆盖任何功能.编译器不会为Drived
生成vtable
,因为它只是Base
s的副本.
The reason _vptr.Base
appears in Derived
is because you didn't override any functions. The compiler doesn't generate a vtable
for Drived
because it will just be a duplicate of Base
s.
这篇关于与派生类的虚拟指针混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!