is there any need for virtual when no inheritance is involved? I think that virtual function or keywork is tightly coupled with inheritance as per my level of understanding and knowledge. Am I right? Is there any place where virtual function comes to use other than with inheritance.(Base and derived classes)?
Yes, you are right.
Even more: virtual functions are only needed for runtime polymorphism, which is only a part of what inheritance is about.
no, you are right, there is no use of virtual functions outside of inheritance, because virtual functions are specifically made in order to allow derived class to "override" base class functions (oftenly extending them by calling them and then do additional treatment)
Virtual is used only where runtime polymorphism is needed. Use of virtual make sure that correct version (BASE/DERIVED) of the method is getting called and the call is resolved at runtime according the type of caller object. For more refer to Virtual Functions
and YES, your understanding is correct.
Related
Is there any reason to declare a method virtual if a class has no subclasses, and is always used directly?
For example:
class Foo {
public:
virtual void DoBar {
// Do something here.
}
}
I came across this in some code I was reading, and couldn't find any justification.
Thanks!
Well the essence of virtual keyword is directly related to inheritance. This is an extract from CPP Ref:-
Virtual members A virtual member is a member function that can be
redefined in a derived class, while preserving its calling properties
through references. The syntax for a function to become virtual is to
precede its declaration with the virtual keyword
So IMHO - the ans to your question is no - it makes no sense - unless the code has changed from initial implementation - and trust me that happens a lot!
It is useful when writing library code to keep the future programmer in mind who may want to extend the class and provide their own behaviour. For example it is common to have a virtual Paint() function or virtual mouse handling functions in GUI libraries. They provide default implementations, but they allow the possibility of extension.
If that class is meant to be derive from then yes it makes sense. These decisions should be made when deciding the architecture of a program, and defining what can be done with the interfaces. If they do not want this to be derived from then it should not be virtual. If they do want it to be derived from then it should be virtual (and it should also make the destructor virtual).
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.
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.
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.
I read different opinions about this question. Let's say I have an interface class with a bunch of pure virtual methods. I implement those methods in a class that implements the interface and I do not expect to derive from the implementation.
Is there a need for declaring the methods in the implementation as virtual as well? If yes, why?
No - every function method declared virtual in the base class will be virtual in all derived classes.
But good coding practices are telling to declare those methods virtual.
virtual is optional in the derived class override declaration, but for clarity I personally include it.
Real need - no. Once a method is declared as virtual in the base class, it stays virtual for all derived classes. But it's good to know which method is virtual and which - not, instead of checking this in the base class. Also, in most cases, you cannot be sure, if your code will be derived or not (for example, if you're developing some software for some firm). As I said, it's not a problem, as once declared as virtual, it stays virtual, but just in case .. (:
There is no requirement to mark them virtual.
I'd start by arguing that virtual advertises to readers that you expect derived classes to override the virtual to do something useful. If you are implementing the virtual to do something, then the virtual method might have nothing to do with the kind of thing your class is: in which case marking it virtual is silly. consider:
class CommsObject {
virtual OnConnect();
virtual OnRawBytesIn();
};
class XMLStream : public CommsObject {
virtual OnConnect();
OnRawBytesIn();
virtual OnXMLData();
};
In that example, OnConnect is documented as virtual in both classes because it makes sense that a descendent would always want to know. OnRawBytesIn doesn't make sense to "Export" from XMLStream as it uses that to handle raw bytes, and generate parsed data - which it notifies via OnXMLData().
Having done all that, I'd then argue that the maintainer of a 3rd class, looking at XMLStream, might think that it would be "safe" to create their own OnRawBytes function and expect it to work as a normal overloaded function - i.e. the base class would call the internal correct one, and the outer one would mask the internal OnRawBytes.
So omitting the virtual has hidden important detail from consumers of the class and made the code behave in unexpected ways.
So ive gone full circle: Don't try to use it as a hint about the intended purpose of a function - DO use it as a hint about the behaviour of the function: mark functions virtual consistently so downstream programmers have to read less files to know how a function is going to behave when overridden.
No, it is not needed and it doesn't prevent any coding errors although many coders prefer to put it.
Once C++0x becomes mainstream you'll be able to use the override specifier instead.
Once 'virtual', it's virtual all the way down to the last child. Afaik, that's the feature of the c++.
If you never derive from a class then there is no point making its methods virtual.