How many V table will be created in the following code? - c++

class base{
public:
virtual void fn() {
}
};
class der1 : public base {
void fn() {
}
};
class der2 : public der1 {
virtual void fn() {
}
};
I have another question.In definition of class der1, I have not mention "virtual" while redefining function fn. Has it any effect while creating V table

As already mentioned, vtable is a compiler/platform specific implementation detail, so there is no general answer.
I have another question.In definition of class der1, I have not mention "virtual" while redefining function fn. Has it any effect while creating V table
Since the function fn() has been defined as virtual in the base class, all subclass implementations are also virtual by definition (thus overriding the base class implementation), regardless of whether they are explicitly declared so. So the vtable will contain them (if the specific compiler generates one).
You can easily test this by making base::fn() pure virtual. If declaring der1::fn() virtual made a difference, you could not instantiate der1 without it.

So, as the pedantic answers implied: the C++ language does not mention v-tables, it's an implementation details that all major compilers used, as it's relatively simple and very efficient (because it's so used, optimizations are well-known).
With that said, the typical answer is that there will be one v-table per class containing virtual functions. Some may be optimized out, if proved to be unused.
Typically, it could be unnecessary to generate a v-table for an abstract class, as it cannot be instantiated. However calling virtual functions in constructors and destructors is still allowed (though the effects are not always those expected), so compilers usually generate a v-table and simply set the entries to the pure virtual functions to null.
Therefore, your answer is probably 3.
The following implies a compiler such as GCC which implements the Itanium C++ ABI.
You can actually verify this 3 by generating a library and dumping the symbols (v-tables and typeinfo symbols are generated for classes with virtual functions):
$ nm somelib.so | grep Foo
00000000012a48b0 V _ZTIN3FooE
0000000000e0fca0 V _ZTSN3FooE
00000000012a4620 V _ZTVN3FooE
$ nm somelib.so | grep Foo | c++filt
00000000012a48b0 V typeinfo for Foo
0000000000e0fca0 V typeinfo name for Foo
00000000012a4620 V vtable for Foo
The prefixes to look for are _ZTIN, _ZTSN and _ZTVN for (resp.) the typeinfo, typeinfo name and vtable.

There can be no concrete answer for this because Virtualism is left out as an implementation detail of compilers.
The C++ standard does not talk about vptr or vtable at all. The answer for this can vary from each compiler to compiler.

How many V table will be created in the following code?
The question can not be answered.
Nor do you want to know, nor should you care. It makes no difference in how your code is used or works.
I have another question.
Ok Listening.
In definition of class der1, I have not mention "virtual" while redefining function fn.
Because the definition of 'void fn()' is exactly the same as in the base class it inherits the virtual attribute of the function it is overriding. Thus it is also virtual.
Has it any effect while creating V table
There is no way to tell. As V-Table have nothing to do with the C++ language (they are what the compiler does behind the code, if it even uses a V-table (which it may not)).

Related

Does it make any difference if a virtual method is declared virtual in the subclass? [duplicate]

This question already has answers here:
virtual qualifier in derived class
(4 answers)
Closed 7 years ago.
Quite often I see code (e.g. here) where the override is also declared virtual even if the class is not meant to be subclassed again. E.g.
class A {
virtual void foo();
}
class B : public A {
virtual void foo();
}
// there is no subclass of B (and most likely there will never be one)
In my naive C++ beginners thinking, I find it much clearer and more explicit not to declare B::foo virtual in case it is not meant to be overridden. I.e.
class B : public A {
void foo();
}
Many methods I write are not meant to be overridden. On the other hand I understand virtual as indication that the method was designed to be overridden. I guess it is just a matter of taste, however I am not 100% sure:
Does it make any difference if B::foo() is declared virtual (assuming B will not be used as base class)?
There is no requirement to mark an overriden virtual method virtual in a derived class. The decision whether a method is virtual or not is made in the least derived class.
It is, however, a good idea to mark a virtual method explicitly virtual in a derived class for two reasons:
It serves as documentation for future readers of your code. That could be you, so this should be a strong incentive.
If someone decides to remove the virtual qualifier in the base class, a compiler can catch the bug before the application ships, and issue a warning. There is no requirement for a particular implementation to issue a diagnostic in this case, though.
If your compiler supports C++11, using the override specifier in derived classes is recommended, as it performs additional validation. It is required for an implementation to issue an error, if a base class method is not declared virtual, but the derived class uses an override specifier.
No, it doesn't make any difference. If A::foo is declared as virtual in the base class, B::foo is also virtual: whether you declare it as such or not.
A method doesn't lose is virtual qualifier, so if A::foo() is virtual, B::foo() is also virtual even without repeating the keyword in B::foo() declaration.
Before override, it may be a style to repeat virtual in derived classes to remember that it is a overridden method, now we can use override instead (and compiler check that it is correct whereas it can't do it simply with virtual)
Many methods I write are not meant to be overridden
So you may mark them as final to forbid the method to be overridden (you may also mark the class final if it makes sense).

Is there any sense in marking a base class function as both virtual and final? [duplicate]

This question already has answers here:
What's the point of a final virtual function?
(11 answers)
Closed 5 years ago.
In various explanations of C++11's final keyword, I'm seeing examples like this.
class base
{
public:
virtual void f() final;
};
class derived : public base
{
public:
virtual void f(); // Illegal due to base::f() declared final.
};
Is this actually a useful use of final? Why would you declare a virtual function in a base class (implying that it will be usefully overrideable in derived classes) and then immediately mark it as final (negating that implication)? What is the utility of virtual void f() final?
I can see the value of marking derived::f() final rather than base::f(). In this case, base::f() presumably had a good design-based reason for why f() should be virtual, and derived::f() separately has a good design-based reason for why no further-derived class should override its implementation.
If you don't want the function overridden polymorphically, why not just leave off the virtual keyword? Of course, derived classes might still override the function non-polymorphically. Is the purpose of virtual void f() final in the base class therefore to make base::f() firmly non-overrideable in any way—either as a virtual or non-virtual function? If so, then it seems a bit unfortunate that we must add the virtual keyword in this case only to enable use of final. I would think that it should then be legal to mark even non-virtual functions as final.
Why use virtual void f() final for a function originating in a base class when the sense of virtual and the sense of final seem to contradict?
Is there any sense in marking a base class function as both virtual and final?
Yes, at least temporarily.
I found myself in a relatively large and unfamiliar existing C++ source code base. Much of the code was written prior to C++11. I found that I wanted to ensure that all overrides of a virtual function in a base class were marked with override. The hard part is locating all of those overrides.
I marked the virtual function in the base class with final, and the compiler quickly showed me where every single override was declared. It was then very easy to decorate the overrides how I wanted, and remove the final from the virtual in the base class.
You can mark it virtual to indicate that it is 'virtual' in the class you are inheriting from (even though you don't have to do this), and mark it final to indicate that no class deriving from your class may override it further. This may happen when you are implementing an abstract base class, for example. This is C++11, so it's not useful; override is a much better indication, since it is enforced by the compiler.
Another possibility: you want this method not to be overridden, but you want to be able to change that without recompilation. Remember that virtual means it is in the virtual table. even if the compiler will not let you override it.
I think the purpose of the example you have shown is to demonstrate priorities between virtual and final, and nothing more. It is a minimal use of final, not a useful one.
Marking a non-virtual method as final makes no sense, since you cannot override them anyway. If you want the compiler to prevent hiding, that is a completely different issue, that has nothing to do with the method being final. In a sense, non-virtual methods are final already, but hidable.
The alternative is a non-virtual function. But non-virtual function can be hidden by a derived class. So if you want to prevent a function hiding, it can be specified as virtual final one.

Interface vtable

Do interfaces (polymorphic class solely with pure virtual functions) have a vtable?
Since interfaces do not implement a polymorphic function themself and cant be directly constructed there would be no need for the linker to place a vtable. Is that so? Im especially concerned about the MSVC compiler.
Yes, they do. And there are a number of good reasons for that.
The first good reason is that even pure virtual methods have implementation. Either implicit or explicit. It is relatively easy to pull off a trick calling a pure virtual function, so you can basically provide a definition for one of yours, call it and see what happens. For that reason, there should be a virtual table in a first place.
There is another reason for putting a virtual table into a base class even if all of its methods are pure virtual and there are no other data members though. When polymorphism is used, a pointer to a base class is passed all around the program. In order to call a virtual method, compiler/runtime should figure out the relative offset of the virtual table from the base pointer. If C++ had no multiple inheritance, one could assume a zero offset from the abstract base class (for example), in which case it would have been possible not to have a vtable there (but we still need it due to reason #1). But since there is a multiple inheritance involved, a trick ala "vtable is there at 0 offset" won't work because there could be two or three vtables depending on a number (and type) of base classes.
There could be other reasons I haven't though of as well.
Hope it helps.
From a purely C++ point of view it's an academic question. Virtual functions don't have to be implemented with vtables, if they are there is no portable way to get at them.
If you're particular concerned about the MSVC compiler you might want to decorate your interfaces with __declspec(novtable).
(In general, in common implementations, an abstract class may need a vtable, e.g.:
struct Base {
Base();
virtual void f() {}
virtual void g() = 0;
};
void h(Base& b) {
b.f(); // Call f on a Base that is not (yet) a Derived
// vtable for Base required
}
Base::Base() {
h(*this);
}
struct Derived : Base {
void g() {}
};
int main() {
Derived d;
}
)
The vtable is not necessary, but rarely optimized out. MSVC provides the __declspec(novtable) extension, which tells the compiler explicitly that the vtable can be removed. In the absence of that, the compiler would have to check itself that the vtable is not used. This is not exceptionally hard, but still far from trivial. And since it doesn't provide real speed benefits in regular code, the check is not implemented in any compiler I know.

C++ Interview: vtable for a class with a pure virtual function

I was asked this interview question today!! (it was a really awkward telephonic interview..):
What is the difference between the vtable for a class with virtual
functions and a class with pure virtual functions?
Now, I know the C++ standard doesn't specify anything about vtables, or even the existence of a v-table ..however theoretically speaking what would the answer be?
I blurted out that the class with a pure virtual function could have a vtable and its vtable entry for the pure virtual function will point to the derived class implementation. Is this assumption correct? I did not get a positive answer from the interviewer.
Will a hypothetical compiler create a vtable for a class with only pure virtual functions? What if the class contains pure virtual functions with definitions? (as shown in : http://www.gotw.ca/gotw/031.htm).
In the case of non-pure virtual functions, each entry in the vtable will refer to the final-overrider or a thunk that adapts the this pointer if needed. In the case of a pure-virtual function, the entry in the vtable usually contains a pointer to a generic function that complains and aborts the program with some sensible message (pure virtual function called within this context or similar error message).
Will a hypothetical compiler create a vtable for a class with only pure virtual functions?
Yes, it will, the difference will be in the contents stored in the table, not in the shape of the table. In a simplistic approach, a NULL pointer for pure virtual functions, non-NULL for virtual functions. Realistically, a pointer to a generic function that will complain and abort() with usual compilers.
What if the class contains pure virtual functions with definitions?
This will not affect the vtable. The vtable is only used for dynamic dispatch, and a call will never be dynamically dispatched to the definition of a pure virtual function (i.e. you can only manually dispatch to the pure virtual function by disabling dynamic dispatch qualifying the name of the type: x.base::f() will call base::f even if it is pure-virtual, but x.f() will never be dispatched to base::f if it is pure virtual.
An implementation can do pretty much anything in such cases, because if
your code ends up calling a pure virtual function in a context where
dynamic resolution is required, and it would resolve to a pure virtual
function, the behavior is undefined. I've seen several different
solutions: the compiler inserts the address of a function which
terminates with an error message (the preferred solution from a
quality of implementation point of view), the compiler inserts a null
pointer, or the compiler inserts the address of the function from some
derived class. I've also seen cases where the compiler will insert the
address of the function if you provide an implementation. The only
correct answer to the question is that you can't count on any particular
behavior.
I can tell you that "pure" abstract classes (classes with only pure virtual functions) are used by Microsoft (and MS VC++) for their COM interfaces. Perhaps he was speaking of it. The "internal" representation of a COM is a pointer to a vtable. Pure abstract classes in MS VC++ are implemented in the same way, so you can use them to represent COM objects. Clearly if you class has other virtual functions, you can't simply overwrite its vtable with the COM vtable :-)

Do all classes have a Vtable created for them by the compiler?

There are many resources online about VTables. They commonly have the same statement regarding them:
"Whenever a class itself contains virtual functions or overrides virtual functions from a parent class the compiler builds a vtable for that class. This means that not all classes have a vtable created for them by the compiler. The vtable contains function pointers that point to the virtual functions in that class. There can only be one vtable per class, and all objects of the same class will share the same vtable."
So why exactly does this mean that not all classes have a vtable created for them by the compiler? Is it because somc classes don't have virtual functions?
Precisely. Some classes don't have a vtable because they don't have any virtual methods.
Virtual methods are methods for which your compiler cannot generate a direct call because it varies depending on the implementation of the class. Vtables are a kind of lookup table that solve this problem by delaying the decision of which implementation to call during the run time of your program: instead of generating a function call, your compiler generates a method lookup on the vtable, then calls the returned method.
Take this example:
class Foo
{
public:
virtual void vMethod()
{
std::cout << "Foo::vMethod was called!" << std::endl;
}
};
class Bar : public Foo
{
public:
virtual void vMethod()
{
std::cout << "Bar::vMethod was called!" << std::endl;
std::cout << "This is not the same as Foo::vMethod." << std::endl;
}
};
Foo* foo = new Bar;
foo->vMethod();
This will print Bar's message. In most non-trivial scenarios, your compiler cannot know in advance the type of the object on which a virtual method is called. As mentioned above, the vtable solves the problem by providing a uniform lookup mechanism to find method implementations, no matter the type of an object.
A vtable pointer must exist in every instance of a class (which requires the size of a pointer of additional memory, likely to be 4 or 8 bytes), and some insignificant amount of statical memory somewhere in your program's address space. This may not seem a lot to you (and indeed many people would agree), but this can be cumbersome in certain scenarios (like embedded systems where memory is extremely limited). Having vtables for each class would violate the general C++ principle that you pay only for what you use, and therefore the compiler doesn't generate any vtable if it doesn't have to.
Not having a vtable has the notable side effect of disabling runtime type information. If you need to use RTTI in your code, your classes must have at least one virtual method. The convention is to mark the destructor virtual in these cases.
Actually, nothing in C++ requires that any class has a vtable - it's entirely an implementation issue. However, a class with virtual functions must somehow support polymorphic function calls, and this will always require a table/map of some sort. This table/map will be created by the compiler for classes that have polymorphic functions, and might (depending on compiler quality) be created for those that don't.
In addition, some classes don't have a vtable because is explicitly removed, see __declspec(novtable) (compiler specific)