How many virtual table is created for the following code?

Viewed 372

I am learning c++ and got one question about the virtual table ,help me in understanding this. I want to know how many tables are created in this program.

 #include <iostream>
    class A { public: virtual void f() { } };
    class B : public A { };
    class C : public B { };
2 Answers

How many virtual table is created for the following code?

The C++ language does not define such thing as a virtual table. It is a way to implement virtual dispatch. Since it is an implementation detail, the number of virtual tables is not defined by the language either and it is up to the language implementation to decide.

As such, there is no answer unless the question is restricted to some particular language implementation. Using an example language implementation, a virtual table was created for each of these classes:

std::exception
std::bad_exception
std::type_info
std::bad_cast
std::bad_typeid
std::bad_alloc
std::bad_array_new_length
std::nested_exception
__cxxabiv1::__forced_unwind
std::locale::facet
std::__cxx11::collate<char>
std::__cxx11::collate<wchar_t>
std::__cxx11::collate_byname<char>
std::__cxx11::collate_byname<wchar_t>
std::logic_error
std::domain_error
std::invalid_argument
std::length_error
std::out_of_range
std::runtime_error
std::range_error
std::overflow_error
std::underflow_error
std::_V2::error_category
std::system_error
std::ios_base::failure
std::ios_base
std::basic_streambuf<char>
std::basic_streambuf<wchar_t>
std::ctype<char>
std::__ctype_abstract_base<wchar_t>
std::ctype<wchar_t>
std::ctype_byname<char>
std::ctype_byname<wchar_t>
std::__cxx11::numpunct<char>
std::__cxx11::numpunct<wchar_t>
std::__cxx11::numpunct_byname<char>
std::num_get<char>
std::num_put<char>
std::__cxx11::numpunct_byname<wchar_t>
std::num_get<wchar_t>
std::num_put<wchar_t>
std::basic_ios<char>
std::basic_ios<wchar_t>
std::basic_ostream<char>
std::basic_ostream<wchar_t>
std::basic_istream<char>
std::basic_istream<wchar_t>
std::basic_iostream<char>
std::basic_iostream<wchar_t>
A
B
C

Here is the command I used to generate the list:

g++ -fdump-lang-class -std=c++17 main.cpp \
    && grep Vtable main.cpp.*.class \
     | cut -f 3 -d ' '

The answer is 3 virtual tables. You have created 3 classes here, so that means this code will be having 3 virtual tables.

Related