c++11 - Why does making this virtual destructor inline fix a linker issue? -


if have pure virtual class interfacea consists solely of pure virtual destructor, why have define destructor inline? i don't error when try link it.

below admittedly contrived example, illustrates point. point not compile me using cmake , g++. however, if change interfacea destructor definition follows - inline interfacea::~interfacea(){}; compiles.

why this? inline keyword do?

// interfacea.h, include guards ommitted clarity class interfacea {     public:         virtual ~interfacea() = 0; };  interfacea::~interfacea(){};  // a.h, include guards ommitted clarity #include "interfacea.h" class : public interfacea {     public:         a(int val)             : myval(val){};         ~a(){};          int myval; };  // auser.h, include guards ommitted clarity #include "interfacea.h" class auser {     public:         auser(interfacea& ana)             : mya(ana){};         ~auser(){};          int getval() const;      private:         interfacea& mya; };  // auser.cpp #include "auser.h" #include "a.h"  int auser::getval() const {     a& ana = static_cast<a&>(mya);     return ana.myval; }  // main.cpp #include "auser.h" #include "a.h" #include <iostream>  int main(){     ana(1);     auser user(ana);     std::cout << "value = " << user.getval() << std::endl;     return 0; } 

you have use inline keyword when defining functions in header files. if not, , file included in more 1 translation unit, function defined twice (or more times).

the linker error "symbol ... multiply defined" right?

if defined member function in body of class, implicitly inline , work.

see this answer

to answer question "what inline keyword do?":

in old days used ask compiler inline functions i.e. insert code whenever function used instead of adding function call. turned simple suggestion since compiler optimizers became more knowledgeable functions inline candidates. these days used exclusively define functions in header files must have external linkage.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - VueJS2 and the Window Object - how to use? -