So here is code sample. The task was to give output that this code will print out. Is it 2 different functions? What happens with vtable in B class then? Does it just store 2 pointers on 2 different functions with same name?
#include<iostream>
#include <vector>
using namespace std;
class A
{
public:
A()
{
init();
}
virtual void init(bool a = true)
{
if(a)
cout << "A" << endl;
}
};
class B :public A
{
public:
virtual void init()
{
cout << "B" << endl;
}
};
int main()
{
B b;
A* a = &b;
a->init();
a->init(true);
system("pause");
}
Couldn't really find where to read about this case. Could you mates explain or give a link to some source if you've seen this case?
They were already two different functions (overriding doesn't change that), but because they have a different signature, the one in B
does not override the one in A
.
Remember, the name of a function is only part of its identity! Its parameter list matters too.
If you'd put the override
keyword on B::init()
then your program would have failed to compile because B::init()
doesn't actually override anything (there is no init()
, virtual or otherwise, in its base).
Nothing really "happens" with the vtable that wouldn't also have happened if the two functions literally had different names, like A::init(bool)
and B::urgleburgleboop()
.
Note that, quite aside from virtual
and polymorphism and overriding, B::init()
also "hides" A::init(bool)
for normal overload resolution (thanks, C++!), and because of this Clang will warn on your code.
As for where you can read about it, your C++ book would be a good start. :)