lundi 14 août 2017

Why does making this virtual destructor inline fix a linker issue?

If I have a pure virtual class InterfaceA that consists solely of a pure virtual destructor, why do I have to define the destructor as inline? I I don't I get an error when I try to link it.

Below is an admittedly contrived example, however it illustrates the point. The point does not compile for me using cmake and g++. However, if I change the InterfaceA destructor definition as follows - inline InterfaceA::~InterfaceA(){}; then it compiles.

Why is this? What does the inline keyword do?

// InterfaceA.h, include guards ommitted for clarity
class InterfaceA
{
    public:
        virtual ~InterfaceA() = 0;
};

InterfaceA::~InterfaceA(){};

// A.h, include guards ommitted for clarity
#include "InterfaceA.h"
class A : public InterfaceA
{
    public:
        A(int val)
            : myVal(val){};
        ~A(){};

        int myVal;
};

// AUser.h, include guards ommitted for 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(){
    A anA(1);
    AUser user(anA);
    std::cout << "value = " << user.getVal() << std::endl;
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire