开发者

Where is pure virtual function located in C++?

Which virtual table will be pure virtual f开发者_开发知识库unction located? In the base class or derived class?

For example, what does the virtual table look like in each class?

class Base {

  virtual void f() =0;
  virtual void g();
}


class Derived: public Base{

  virtual void f();
  virtual void g();

}


g++ -fdump-class-hierarchy layout.cpp produces a file layout.cpp.class. The content of layout.cpp.class will show the following:

Vtable for Base
Base::_ZTV4Base: 4u entries
0     (int (*)(...))0
8     (int (*)(...))(& _ZTI4Base)
16    __cxa_pure_virtual
24    Base::g

Class Base
   size=8 align=8
   base size=8 base align=8
Base (0x7ff893479af0) 0 nearly-empty
    vptr=((& Base::_ZTV4Base) + 16u)

Vtable for Derived
Derived::_ZTV7Derived: 4u entries
0     (int (*)(...))0
8     (int (*)(...))(& _ZTI7Derived)
16    Derived::f
24    Derived::g

Class Derived
   size=8 align=8
   base size=8 base align=8
Derived (0x7ff893479d90) 0 nearly-empty
    vptr=((& Derived::_ZTV7Derived) + 16u)
  Base (0x7ff893479e00) 0 nearly-empty
      primary-for Derived (0x7ff893479d90)

Removing the 'pureness' of f changes the fifth line to:

16    Base::f


Each class has its own vtable. The entry for f in Base will be NULL, and the entry in Derived will be a pointer to the code for the implemented method.


The vtable entry will be in the base class.

Why? Because you can have a base pointer type that holds a derived type object's address and still call the method on the base type's pointer variable.

Pure virtual simply tells the compiler that the derived types must provide their own implementation, and they cannot rely on the base class' implementation (if one is even specified in the base class)


In both actually. The base class vtable will have a slot for the pure virtual function pointing to something like pure_virtual_function_called() stub that would probably abort the program, while the derived class vtable will have a pointer to the actual implementation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜