I encountered a problem while I was studying about C++ virtual functions. The code is as follows:
#include <iostream>
#include<string>
using namespace std;
class Event {
public:
string name;
virtual string getEvent();
void setName(string name) {
this -> name = name;
}
};
class Sports: public Event {
public: string getEvent() {
return name;
}
};
int main() {
Sports s;
Event *ptr;
ptr = &s;
s.setName("Chess");
cout << "Event Name: " << ptr -> getEvent() << endl;
return 0;
}
And I am getting the following compilation error:
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\hp\AppData\Local\Temp\cciS3jrR.o:main.cpp:(.text$_ZN5EventC2Ev[__ZN5EventC2Ev]+0xa): undefined reference to `vtable for Event'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\hp\AppData\Local\Temp\cciS3jrR.o:main.cpp:(.text$_ZN5EventD2Ev[__ZN5EventD2Ev]+0xa): undefined reference to `vtable for Event'
collect2.exe: error: ld returned 1 exit status
After some experiments, I came to know that if I define the virtual function in the base class, the program compiles fine. Can someone please guide me and tell me what I'm missing here? I expected the output to be Event Name: Chess, it would be really helpful if someone could explain to me why won't I get the expected output.