I read about it in other questions but none of them was similar, some was about to call a virtual method in the constructor, others about pure virtuals, but the question here is about vituais methods that are not pure, but about virtual methods that doesn't need be implemented in all derivatives classes. If the class instantiated doesn't implements the method, if we call, it logically calls the method from the base and it crashes sometimes. I was wondering, why? What is VTABLE (where it enters)? And what is the best way to solve it.
This is a simple example, (avoid answer like pure virtual).
#include <iostream>
class Foo
{
public:
virtual std::string myString() {}
};
class Bar : public Foo
{
public:
};
int main(int argc, char ** argv)
{
Foo * bar = new Foo;
bar->myString();
return 0;
}
What would be the best solution?
- Throw an exception
- Using assert(false)
- Returning a default value
- Avoid implementing a body and it will result in an error in compilation time
- None of the alternatives
The best answer will be the one that explains why this happen based on VTABLE and of course, that choose one solution and explain why. The idea is not to base it on opinions.
The base class does implement the function, it just implements it wrong. It is not related to vtables or anything sophisticated. Solution 4 preferred (since it prevents building wrong programs), if not possible/desired 1 or 2 in that order.
Note that the error is not at all related to virtual functions, or inheritance in general (you do not use
Bar, did you notice?). It is not even related to classes at all but would happen with any freestanding function as well. Consider:In order to prevent the error from happening with your original code, just return a value. If you implement the function and don't throw or abort (which are the three alternatives), i.e. if you return, you must return a value: