Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is pure virtual function located in C++?

Tags:

c++

vtable

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();

}
like image 279
skydoor Avatar asked Mar 31 '10 02:03

skydoor


People also ask

Where is pure virtual function defined?

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 {

What is a pure virtual function in C?

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.

Which class contains pure virtual function?

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.

Can we define pure virtual function in base 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.


1 Answers

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
like image 88
Artem Sokolov Avatar answered Nov 06 '22 07:11

Artem Sokolov