Which virtual table will be pure virtual function 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();
}
A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be “pure” using the curious =0 syntax. For example: class Base {
A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract. Classes containing pure virtual methods are termed "abstract" and they cannot be instantiated directly.
A class that contains a pure virtual function is known as an abstract class. In the above example, the class Shape is an abstract class. We cannot create objects of an abstract class.
A pure virtual function is a member function of base class whose only declaration is provided in base class and should be defined in derived class otherwise derived class also becomes abstract. Classes having virtual functions are not abstract. Base class containing pure virtual function becomes abstract.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With