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

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.

Related

Is there any reason to declare a method virtual without inheritance?

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

virtual functions when there no inheritance involved

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.

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.

If a class might be inherited, should every function be virtual?

In C++, a coder doesn't know whether other coders will inherit his class. Should he make every function in that class virtual? Are there any drawbacks? Or is it just not acceptable at all?
In C++, you should only make a class inheritable from if you intend for it to be used polymorphically. The way that you treat polymorphic objects in C++ is very different from how you treat other objects. You don't tend to put polymorphic classes on the stack, or pass them by or return them from functions by value, since this can lead to slicing. Polymorphic objects tend to be heap-allocated, be passed around and returns by pointer or by reference, etc.
If you design a class to not be inherited from and then inherit from it, you cause all sorts of problems. If the destructor isn't marked virtual, you can't delete the object through a base class pointer without causing undefined behavior. Without the member functions marked virtual, they can't be overridden in a derived class.
As a general rule in C++, when you design the class, determine whether you want it be inherited from. If you do, mark the appropriate functions virtual and give it a virtual destructor. You might also disable the copy assignment operator to avoid slicing. Similarly, if you want the class not to be inheritable, don't give it any of these functions. In most cases it's a logic error to inherit from a class that wasn't designed to be inherited from, and most of the times you'd want to do this you can often use composition instead of inheritance to achieve this effect.
No, not usually.
A non-virtual function enforces class-invariant behavior. A virtual function doesn't. As such, the person writing the base class should think about whether the behavior of a particular function is/should be class invariant or not.
While it's possible for a design to allow all behaviors to vary in derived classes, it's fairly unusual. It's usually a pretty good clue that the person who wrote the class either didn't think much about its design, lacked the resolve to make a decision.
In C++ you design your class to be used either as a value type or a polymorphic type. See, for example, C++ FAQ.
If you are making a class to be used by other people, you should put a lot of thought into your interface and try to work out how your class will be used. Then make the decisions like which functions should be virtual.
Or better yet write a test case for your class, using it how you expect it to be used, and then make the interface work for that. You might be surprised what you find out doing it. Things you thought were absolutely necessary might turn out to be rarely needed and things that you thought were not going to be used might turn out to be the most useful methods. Doing it this way around will save you time not doing unnecessary work in the long run and end up with solid designs.
Jerry Coffin and Dominic McDonnell have already covered the most important points.
I'll just add an observation, that in the time of MFC (middle 1990s) I was very annoyed with the lack of ways hook into things. For example, the documentation suggested copying MFC's source code for printing and modifying, instead of overriding behavior. Because nothing was virtual there.
There are of course a zillion+1 ways to provide "hooks", but virtual methods are one easy way. They're needed in badly designed classes, so that the client code can fix things, but in those badly designed classes the methods are not virtual. For classes with better design there is not so much need to override behavior, and so for those classes making methods virtual by default (and non-virtual only as active choice) can be counter-productive; as Jerry remarked, virtuals provide opportunites for derived classes to screw up.
There are design patterns that can be employed to minimize the possibilities of screw-ups.
For example, wrapping internal virtuals in exposed non-virtual methods with sanity checks, and, for example, using decoupled event handling (where appropriate) instead of virtuals.
Cheers & hth.,
When you create a class, and you want that class to be used polymorphically you have to consider that the class has two different interfaces. The user interface is defined by the set of public functions that are available in your base class, and that should pretty much cover all operations that users want to perform on objects of your class. This interface is defined by the access qualifiers, and in particular the public qualifier.
There is a second interface, that defines how your class is to be extended. At that level you have to think on what behavior you want to be overridden by extending classes, and what elements of your object you want to provide to extending classes. You offer access to derived classes by means of the protected qualifier, and you offer extension points by means of virtual functions.
You should try to follow the Non-Virtual Interface idiom whenever possible. That idiom (google for it) basically tries to fully separate the two interfaces by not having public virtual functions. Users call non-virtual functions, and those in turn call on configurable functionalities by means of protected/private virtual functions. This clearly separates extension points from the class interface.
There is a single case, where virtual has to be part of the user interface: the destructor. If you want to offer your users the ability to destroy derived objects through pointers to the base, then you have to provide a virtual destructor. Else you just provide a protected non-virtual one.
He should code the functions as it is, he shouldn't make them virtual at all, as in the circumstances specified by you.
The reasons being
1> The CLASS CODER would obviously have certain use of functions he is using.
2> The inherited class may or may not make use of these functions as per requirement.
3> Any function may be overwritten in derived class without any errors.

Should methods that implement pure virtual methods of an interface class be declared virtual as well?

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.