Is it essential to have a definition for a virtual function?
Consider this sample program below:
#include <iostream>
using namespace std;
class base
{
public:
void virtual virtualfunc();
};
class derived : public base
{
public:
void virtualfunc()
{
cout << "vf in derived class\n";
}
};
int main()
{
derived d;
return 0;
}
This gives the link-error:
In function
base::base()
:: undefined reference tovtable for base
I do not have the definition for the virtual function in base class. Why is this error occurring even though I have not explicitly invoked the virtual function?
The interesting thing which I find is that if I do not instantiate an object of class derived
, the link error is no longer there. Why is this? What has instantiation got to do with the above link error?
derived
or abase
, why would the linker have to do anything with any method from those two classes? If the classes aren't referenced, the linker has no reason to even try to look them up in the object files. (Unless you're building a library.) – Underwrite