3

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)
0

6 Answers 6

12
virtual int add(int a, int b);

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.

virtual int add(int a, int b) = 0;

This is a declaration of a pure virtual function. It does not require a definition, which is why won't get the error.

2

You are getting linker error, because c1::add(int,int) is not implemented. either make it pure virtual or implement it.

2

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:

class c1{
public:
    c1(){}
    ~c1(){}

    virtual int add(int a, int b) = 0;  // adding = 0 makes the function pure virtual

private:
protected:


};
1

change virtual int add(int a, int b); to virtual int add(int a, int b) = 0;

1

virtual int add(int a, int b); This means "my function add can be subclassed". In other to be "my function add can be subclassed and is pure virtual" you need

virtual int add(int a, int b) = 0;
1

c1.add is not pure virtual, you must add = 0.

virtual int add(int a, int b) = 0; 
2
  • 1
    There is no reason why he would have to use public inheritance, unless he wants to downcast pointers to c2 to c1*, which he doesn't do in his example. He can still call c2::add from his main, since it is a public function.
    – Agentlien
    Jan 17, 2013 at 14:04
  • You are very welcome. I'm glad to see you fixed it so soon. :)
    – Agentlien
    Jan 17, 2013 at 15:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.