Virtual Function simply a function overloading? - c++

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.

Related

How to warn (or error) when calling a function that is only implemented in base but not derived?

I'm really not sure how to title the question briefly.
Situation:
In C++20.
There is a Base as an interface, which specifies all the features (member functions) we have. There are also multiple derived classes that may implement a subset of features. Those functions are virtual functions.
There are also some functions that are identical across all derived classes.
There can be overloaded member functions.
We can statically check if a function is available in certain Derived by using SFINAE or concept.
Requirements:
When calling a non-implemented function by derived, there should be some compile warnings or errors.
As the number of features and derived can increase, I hope I don't need to change (or add) too much when such things happen.
The derived classes should also be able to convert to the base class.
Don't need to do too much for those "identical functions" mentioned in 2..
Maybe solutions (nonperfect):
Implements every feature in the Base and throws the error inside. Use using in Derived and put the function in the private field. Cons. If there's a new feature, we need to add it to every class. If we forget to do so, there's no warning.
Use pure virtual functions in Base and implement them in every Derived for every feature. Cons: A lot of implementations (and code) for those features that the Derived doesn't require, and the implementations are all the same - throw an error.
Update:
For the 11.: by "A lot of implementations", I made an example: https://godbolt.org/z/sW8eKjbhx.
You can mark this function as pure virtual. Then it has to be overriden in derived classes. Still it can have body.
class Base {
public:
virtual void f() = 0;
};
void Base::f() {
// ...
}

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

C++ should I use virtual methods?

Let me start by telling that I understand how virtual methods work (polymorphism, late-binding, vtables).
My question is whether or not I should make my method virtual. I will exemplify my dilemma on a specific case, but any general guidelines will be welcomed too.
The context:
I am creating a library. In this library I have a class CallStack that captures a call stack and then offers vector-like access to the captured stack frames. The capture is done by a protected method CaptureStack. This method could be redefined in a derived class, if the users of the library wish to implement another way to capture the stack. Just to be clear, the discussion to make the method virtual applies only to some methods that I know can be redefined in a derived class (in this case CaptureStack and the destructor), not to all the class methods.
Throughout my library I use CallStack objects, but never exposed as pointers or reference parameters, thus making virtual not needed considering only the use of my library.
And I cannot think of a case when someone would want to use CallStack as pointer or reference to implement polymorphism. If someone wants to derive CallStack and redefine CaptureStack I think just using the derived class object will suffice.
Now just because I cannot think polymorphism will be needed, should I not use virtual methods, or should I use virtual regardless just because a method can be redefined.
Example how CallStack can be used outside my library:
if (error) {
CallStack call_stack; // the constructor calls CaptureStack
for (const auto &stack_frame : call_stack) {
cout << stack_frame << endl;
}
}
A derived class, that redefines CaptureStack could be use in the same manner, not needing polymorphism:
if (error) {
// since this is not a CallStack pointer / reference, virtual would not be needed.
DerivedCallStack d_call_stack;
for (const auto &stack_frame : d_call_stack) {
cout << stack_frame << endl;
}
}
If your library saves the call stack during the constructor then you cannot use virtual methods.
This is C++. One thing people often get wrong when coming to C++ from another language is using virtual methods in constructors. This never works as planned.
C++ sets the virtual function table during each constructor call. That means that functions are never virtual when called from the constructor. The virtual method always points to the current class being constructed.
So even if you did use a virtual method to capture the stack the constructor code would always call the base class method.
To make it work you'd need to take the call out of the constructor and use something like:
CallStack *stack = new DerivedStack;
stack.CaptureStack();
None of your code examples show a good reason to make CaptureStack virtual.
When deciding whether you need a virtual function or not, you need to see if deriving and overriding the function changes the expected behavior/functionality of other functions that you're implementing now or not.
If you are relying on the implementation of that particular function in your other processes of the same class, like another function of the same class, then you might want to have the function as virtual. But if you know what the function is supposed to do in your parent class, and you don't want anybody to change it as far as you're concerned, then it's not a virtual function.
Or as another example, imagine somebody derives a class from you implementation, overrides a function, and passes that object as casted to the parent class to one of your own implemented functions/classes. Would you prefer to have your original implementation of the function or you want them to have you use their own overriden implementation? If the latter is the case, then you should go for virtual, unless not.
It's not clear to me where CallStack is being called. From
your examples, it looks like you're using the template method
pattern, in which the basic functionality is implemented in the
base class, but customized by means of virtual functions
(normally private, not protected) which are provided by the
derived class. In this case (as Peter Bloomfield points out),
the functions must be virtual, since they will be called from
within a member function of the base class; thus, with a static
type of CallStack. However: if I understand your examples
correctly, the call to CallStack will be in the constructor.
This will not work, as during construction of CallStack, the
dynamic type of the object is CallStack, and not
DerivedCallStack, and virtual function calls will resolve to
CallStack.
In such a case, for the use cases you describe, a solution using
templates may be more appropriate. Or even... The name of the
class is clear. I can't think of any reasonable case where
different instances should have different means of capturing the
call stack in a single program. Which suggests that link time
resolution of the type might be appropriate. (I use the
compilation firewall idiom and link time resolution in my own
StackTrace class.)
My question is whether or not I should make my method virtual. I will exemplify my dilemma on a specific case, but any general guidelines will be welcomed too.
Some guidelines:
if you are unsure, you should not do it. Lots of people will tell you that your code should be easily extensible (and as such, virtual), but in practice, most extensible code is never extended, unless you make a library that will be used heavily (see YAGNI principle).
you can use encapsulation in place of inheritance and type polymorphism (templates) as an alternative to class hierarchies in many cases (e.g. std::string and std::wstring are not two concrete implementations of a base string class and they are not inheritable at all).
if (when you are designing your code/public interfaces) you realize you have more than one class that "is an" implementation of another classes' interface, then you should use virtual functions.
You should almost certainly declare the method as virtual.
The first reason is that anything in your base class which calls CaptureStack will be doing so through a base class pointer (i.e. the local this pointer). It will therefore call the base class version of the function, even though a derived class masks it.
Consider the following example:
class Parent
{
public:
void callFoo()
{
foo();
}
void foo()
{
std::cout << "Parent::foo()" << std::endl;
}
};
class Child : public Parent
{
public:
void foo()
{
std::cout << "Child::foo()" << std::endl;
}
};
int main()
{
Child obj;
obj.callFoo();
return 0;
}
The client code using the class is only ever using a derived object (not a base class pointer etc.). However, it's the base class version of foo() that actually gets called. The only way to resolve that is to make foo() virtual.
The second reason is simply one of correct design. If the purpose of the derived class function is to override rather than mask the original, then it should probably do so unless there is a specific reason otherwise (such as performance concerns). If you don't do that, you're inviting bugs and mistakes in future, because the class may not act as expected.

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.

Run Code Before Every Function Call for a Class in C++

I would like to run some code (perhaps a function) right before every function call for a class and all functions of the classes that inherit from that class. I'd like to do this without actually editing every function, Is such a thing even possible?
I would settle for having a function called as the first instruction of every function call instead of it being called right before.
AspectC++ is what you want. I haven't used it myself, but Aspect-Oriented Programming paradigm tries to solve this exact problem.
I would suggest using the Non Virtual Interface idiom. All public functions are non-virtual. All virtual functions are protected or private. Public members delegate the calls to virtual members and are usually implemented as inline functions.
This is the way IOStreams are implemented in STL. You can read more about it at C++ Wikibooks.
Intent: To modularize/refactor common before and after code fragments (e.g., invariant checking, acquiring/releasing locks) for an entire class hierarchy at one location.
Regards,
Ovanes
The following might be a bit of an overkill - but how about?
http://msdn.microsoft.com/en-us/library/c63a9b7h.aspx
Another thing you could consider is using something like the [boost/C++0X] shared_ptr wrapper, where you call your custom function on the '->' overload before returning the class instance pointer. It involves modifying usage but not the underlying class, and I've used it a couple times to achieve the same effect. Just another thought.
The somewhat inconvenient way where to build a wrapper class that takes an object of your base type and calls the surrounding function and then the function that you wanted to call. This would be something like a decorator.
The best you can do is to declare a set of virtual functions as protected and have the developers inheriting from the class override the virtual functions. The interface used by the base class can be public, which executes the desired code before passing information to the protected virtual method.
For example:
class Base {
public:
void MyMethod(void) { /* Insert code here */ YourMethod(); }
protected:
virtual void YourMethod(void) {}
};
If the developer knows that he has a specific subclass, he can still bypass your code simply by using a dynamic_cast, and using his own method set. As such, you may want to follow the other suggestions already posted that do not involve the base C++ language.
This sounds like what a profiler does. Have you looked at the source for any profiling tools?
You could also do this with the Curiously recurring template pattern (CRTP).
Using g++, you could use the option -pg for the respective compilation units, which makes the compiler generate a call to the function mcount at the start of every function. mcount is usually provided by profiling tools like gprof, but you can also implement it yourself. You should however make sure that
mcount has C linkage (and is not C++-style name-mangled), i.e. by implementing it as a C function and compiling with a pure C compiler like gcc.
the compilation unit containing mcount is not compiled with -pg.