Does every class have virtual function table in C++ - c++

Does every class have virtual function table in C++?
I know virtual table is for polymorphism. Class with virtual functions must have v-table. But how about class has no virtual function? Or how about class has no base class?

The language specification of C++ does not define what a "vtable" is, or which classes need one.
A particular implementation of C++ in a compiler often uses a vtable to implement virtual methods. If a class has no virtual methods (and no superclasses with virtual methods), then the compiler may omit the vtable. However, keep in mind this is purely a compiler implementation decision, and not required by the standard.

As a non-standard rule of thumb (vtables are not dictated by the standard) which applies to virtually all compilers:
Only classes with virtual member functions and/or a virtual destructor have a vtable. Other classes not. This conforms to the general rule in C++ "pay for what you use".
Of course this puts you into an important responsibility: Is your class to be deleted polymorphically? I.e., will it be used as a public base class and be deleted through it? Then make the destructor virtual.

C++ language as such doesn't talk about how virtual functions needs to be implemented i.e. it can using vtables or any other mechanism. Having said that, generally it is implemented using v-table, and this v-table is created only if the class contains virtual functions.

v-table holds the function's address in it. This table will hold the function address of all the virtual functions that are defined in the base class.
Based on the actual object type, this address changes and the exact function is called.
If the class does not inherits any of the class with virtual function, it need not hold any v-table. All the functions calls will be linked compile time.

Related

Virtual Function simply a function overloading?

So I came across something called Virtual Function in C++, which in a nutshell from what I understood is used to enable function overloading in derived/child classes.
So given that we have the following class:
class MyBase{
public:
virtual void saySomething() { /* some code */ }
};
then when we make a new class that inherits MyBase like this:
class MySubClass : public MyBase{
public:
void saySomething() { /* different code than in MyBase function */ }
};
the function in MySubClass will execute its own saySomething() function.
To understand it, isn't it same as in Java where you achieve the same by simply writing the same name of the function in the derived class, which will automatically overwrite it / overload it?
Where's in C++ to achieve that you need that extra step, which is declaring the function in base class as virtual?
Thank you in advance! :)
Yes you are correct. In Java, all functions are implicitly virtual. In C++ you have a choice: in order to make a function virtual, you need to mark it as such in the base class. (Some folk also repeat the virtual keyword in derived classes, but that is superfluous).
Well in c++ a virtual function comes with a cost. To be able to provide polymorphism, overloading etc you need to declare a method as virtual.
As C++ is concerned with the layout of a program the virtual keywords comes with an overhead which may not be desired. Java is compiled into bytecode and execute in a virtual machine. C++ and native assembly code is directly executed on the CPU. This gives you, the developer, a possibility to fully understand and control how the code looks and execute at assembler level (beside optimization, etc).
Declaring anything virtual in a C++ class creates a vtable entry per class on which the entire overloading thing is done.
There is also compile time polymorphism with templates that mitigates the vtable and resolution overhead which has it's own set of issues and possibilities.
Let's put it this way.
MyBase *ptr; // Pointer to MyBase
ptr = new MySubClass;
ptr->saySomething();
If saySomething is not virtual in MyBase, the base class version will always be called. If it's virtual, then any derived version will be used, if available.
Virtual Function simply a function overloading?
No. "Overloading" means providing multiple functions with the same name but different parameter types, with the appropriate function chosen at compile time. "Overriding" means providing multiple functions within a class heirarchy, with the appropriate function chosen at run time. In C++, only virtual functions can be overridden.
To understand it, isn't it same as in Java where you achieve the same by simply writing the same name of the function in the derived class, which will automatically overwrite it / overload it?
Yes, assuming you mean "override". In Java, methods are overridable by default. This matches Java's (original) philosophy that we should use a 90s-style object-oriented paradigm for everything.
Where's in C++ to achieve that you need that extra step, which is declaring the function in base class as virtual?
Making functions overridable has a run-time cost, so C++ only does that if you specifically request it. This matches C++'s philosophy that you should choose the most appropriate paradigm for your application, and not pay for language facilities you don't need.

When to mark a function in C++ as a virtual?

Because of C++ nature of static-binding for methods, this affects the polymorphic calls.
From Wikipedia:
Although the overhead involved in this dispatch mechanism is low, it
may still be significant for some application areas that the language
was designed to target. For this reason, Bjarne Stroustrup, the
designer of C++, elected to make dynamic dispatch optional and
non-default. Only functions declared with the virtual keyword will be
dispatched based on the runtime type of the object; other functions
will be dispatched based on the object's static type.
So the code:
Polygon* p = new Triangle;
p->area();
provided that area() is a non-virtual function in Parent class that is overridden in the Child class, the code above will call the Parent's class method which might not be expected by the developer. (thanks to the static-binding I've introduced)
So, If I want to write a class to be used by others (e.g library), should I make all my functions to be virtual for the such previous code to run as expected?
The simple answer is if you intend functions of your class to be overridden for runtime polymorphism you should mark them as virtual, and not if you don't intend so.
Don't mark your functions virtual just because you feel it imparts additional flexibility, rather think of your design and purpose of exposing an interface. For ex: If your class is not designed to be inherited then making your member functions virtual will be misleading. A good example of this is Standard Library containers,which are not meant to be inherited and hence they do not have virtual destructors.
There are n no of reasons why not to mark all your member functions virtual, to quote some performance penalties, non-POD class type and so on, but if you really intent that your class is intended for run time overidding then that is the purpose of it and its about and over the so-called deficiencies.
Mark it virtual if derived classes should be able to override that method. It's as simple as that.
In terms of memory performance, you get a virtual pointer table if anything is virtual, so one way to look at it is "please one, please all". Otherwise, as the others say, mark them as virtual if you want them to be overridable such that calling that method on a base class means that the specialized versions are run.
As a general rule, you should only mark a function virtual if the class is explicitly designed to be used as a base class, and that function is designed to be overridden. In practice, most virtual functions will be pure virtual in the base class. And except in cases of call inversion, where you explicitly don't provide a contract for the overriding function, virtual functions should be private (or at the most protected), and wrapped with non-virtual functions enforcing the contract.
That's basically the idea ; actually if you are using a parent class, I don't think you'll need to override every methods so just make them virtual if you think you'll use it this way.

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 :-)

How to define an interface in C++?

I'm working on a C++ class which provides an abstraction of BSD sockets for networking. I want to define an interface ISocket which is implemented by CSocket and MockSocket (the latter for unit testing). I know that I need to define the methods that I want implementing classes to provide as pure virtual, i.e.
class ISocket {
public:
virtual int Socket(int domain, int type, int protocol) = 0;
};
What I'm worried about is whether a class of type ISocket can be instantiated. My instincts tell me that any class with at least one pure virtual method is an abstract class (i.e. interface) and cannot be instantiated, but I have a niggling worry in the back of my mind that I need to do something about the auto-generated constructors and destructor that the C++ compiler will provide (Effective C++ is both a gift--when you remember everything you read in it--and a curse--when you don't).
Am I doing this correctly, or is there a best practise for defining interfaces in C++ that I'm not following here?
In general, you should declare a virtual destructor; otherwise you'll get into undefined behaviour if you try to invoke delete on a pointer-to-interface. There are no such issues with constructors.
Oh, and you are correct that it is not possible to instantiate an object of a class with a pure-virtual.
My instincts tell me that any class with at least one pure virtual method is an abstract class (i.e. interface) and cannot be instantiated
Your instincts are correct on this one. Types with at least one pure virtual function can't be instantiated and will generate a compiler error.
You are doing correct:An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function. You cannot instantiate a virtual class.
You are correct in thinking that any class with a pure virtual method is abstract and cannot be instantiated.
Personally I tend to add a protected destructor to most of my interfaces as in many/most cases I don't want the code that uses the interface to be able to destroy it. Alternatively you should add a public virtual destructor (not pure, with an empty body!) so that the object can be deleted via the interface pointer and the correct destructors will be called.

Set a virtual function declaration to zero? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why pure virtual function is initialized by 0?
In C++, what does it mean to set a function declaration to zero? I'm guessing it has to do with the function being virtual, and not actually defined in this class. Found in a header file of code that I'm reading:
virtual void SetValue(double val)=0;
What's going on here?
It's a pure virtual function. It makes it so you MUST derive a class (and implement said function) in order to use it.
This is called a pure virtual member function in C++ lingo. It means, as you guessed, that the function is not defined within the class, but rather has to be implemented in deriving classes. You cannot instantiate classes with pure virtual member functions, pure virtual functions basically behave like abstract methods in Java or C#.
It means that it is a pure virtual method - which means subclasses must implement the method on their own. There can still be an implementation for that method, but classes with pure virtual methods cannot be instantiated, making this similar to the abstract keyword seen in various other languages.
if you set a virtual function to set, Its called Pure Virtual Functions. And then your class becomes an abstract class.
You can't create instances of that class or any subclasses unless your pure virtual functions are implemented.
The method SetValue is pure virtual. Its class does not provide the implementation of that method, and can not be instantiated (therefore we term it abstract). Concrete derived classes on the other hand have to provide implementations for such methods. See more here.
It means that, the class is abstract, and can't be create its object. It could be used as a base class to another. Pure virtual class is also used in c++ as an interface known from language like java, but of course it is different.
As everyone has mentioned, this means that the function is a pure virtual function. Think of of this as setting the function pointer to null. Classes with pure virtual functions are handled as abstract classes. This means that derived classes must implement this virtual function.
Occasionally, you may encounter what is called a "pure call" error. This means that a pure virtual function was actually called and it will most likely cause the program to crash. The most common cause of a pure call is that the object that the function was called on was already deleted.
"SetValue" is a pure virtual member function that the base class forces derived classes to provide. Pure virtual member functions will have no implementation.
A pure virtual member function specifies that a member function will exist on every object of a concrete derived class even though the member function is not (normally) defined in the base class.
This is because the syntax for specifying a pure virtual member function forces derived classes to implement the member function if the derived classes intend to be instantiated (that is, if they intend to be concrete).
In your case, all objects of classes derived from the base class will have the member function SetValue(). However, because the base class is an abstract concept, it does not contain enough information to implement SetValue().
Imagine that the "= 0" is like saying "the code for this function is at the NULL pointer."
Pure virtual member functions allow users to write code against an interface for which there are several functionally different variants. This means that semantically different objects can be passed to a function if these objects are all under the umbrella of the same abstract base class.