Home > Net >  C why adding word virtual to a function declaration has compilation error?
C why adding word virtual to a function declaration has compilation error?

Time:12-16

I understand why the below code compiled without errors.

class Base{
public:
    int fcn(); // clause 2
};

int main() {
   Base b; // clause 1
}

Reason is at clause 1 no definition are needed for object b. No compilation error. However adding virtual to clause 2 will cause compilation error.

Error:

/usr/bin/ld: /tmp/ccVGJNMU.o: in function `main':
main.cpp:(.text 0x1e): undefined reference to `vtable for Base'
collect2: error: ld returned 1 exit status

Why?

CodePudding user response:

Every non-pure virtual member function is always considered to be odr-used and must therefore have a definition in the program. It doesn't actually need to be called or otherwise referred to in a translation unit to be odr-used as would be the case for other (member) functions.

CodePudding user response:

Only one reason, I think about is, that member class function is implicitly inline. Where do you have a implementation of fcn()? If in the header file, compiler translate it like inline. But if you add virtual, it shouldn't be inline and implementation in .h file could be problem. Try it move to cpp... But, as I wrote, it is only guess, because your information is very poor.

  • Related