I feel like I'm doing something incredibly stupid, but I simply can't figure out what's wrong with my code. I even made a super simplified version of the code and the error still occurs:
#include <iostream>
using namespace std;
class c1{
public:
c1(){}
~c1(){}
virtual int add(int a, int b);
private:
protected:
};
class c2 : c1{
public:
c2(){}
~c2(){}
int add(int a, int b){
return a+b;
}
};
int main(){
c2 c;
c.add(5,6);
}
Can anyone spot what I'm sure is the silliest error of all time?
Here's the exact error message:
1>main.obj : error LNK2001: unresolved external symbol "public: virtual int __thiscall c1::add(int,int)" (?add@c1@@UAEHHH@Z)
c1.add is not pure virtual, you must add = 0.
This is not a declaration of a pure virtual function. It's just a declaration of a virtual function. It lacks a definition, which is why you get the error.
This is a declaration of a pure virtual function. It does not require a definition, which is why won't get the error.
virtual int add(int a, int b);
This means "my functionadd
can be subclassed". In other to be "my functionadd
can be subclassed and is pure virtual" you needchange virtual int add(int a, int b); to virtual int add(int a, int b) = 0;
c1::add()
is not pure virtual, it's just not implemented. This means the linker is correct to look for a body, and correct to complain when it can't find one. You probably meant this:You are getting linker error, because
c1::add(int,int)
is not implemented. either make it pure virtual or implement it.