When I have something like this:
class A
{
virtual void rat();
};
class B : public A
{
virtual void rat() { ; } //implemented!
};
int main(int argc, char **argv)
{
A *a = new B;
delete a;
}
I get linker errors:
unless I make the base rat a pure virtual.
However, when I have this:
class A
{
public:
void rat();
};
int main(int argc, char **argv)
{
A a;
}
This compiles fine and doesn’t give me an undefined reference link error unless I explicitly try to call the rat function in my main (a.rat();). What is the rule on unimplemented base class virtual functions which are, however, implemented in a derived class as in the first failing code snippet?
When both classes define virtual functions, C++ compiler needs to build vtables for both classes
AandB. To buildA‘s vtable, the compiler needsA::rat()– that is where the reference is coming from.When
Ahas no virtual functions, there are no reference toA::ratfrom anywhere, hence you do not get a compile error.As I’m sure you know, you can fix this error by making
A::rata pure virtual, thus providing the needed value for the vtable (in this case, the value is zero).