0

Basically, I'd like to create an interface (C::doTask(double&)) using a virtual base class (A) and let the user to create a concrete class(B). Inside the interface, I use std::bind to pass a virtual struct member function. When compiling the code, I got the error of undefined reference to vtable for XXX.

Any suggestions are appreciated. Thanks!

Here is the header file test.h

#include<functional>
#include<iostream>


typedef std::function<double(double const &)> MyFun;

// base class
struct A
{
    double x;
    // other parameters
    A(){ x = 0.;};
    virtual ~A();
    virtual double fun(double const &x);
};

struct C
{
    MyFun myfun;
    void init(A &a)
    {
        using std::placeholders::_1;
        myfun = std::bind( &A::fun, a, _1 );
    }
    double doTask(double x)
    {
        // do something
        // call myfun 
        return 0.;
    }
};

Here is the main file test.cpp

#include<iostream>
#include "test.h"

// concrete class
struct B:A
{
    // define some other parameters as members
    double a,b;
    B()
    {
        a=1.;
        b=2.;
    }
    double fun(double const &x) override
    {
        return a+b+x;
    }
};


int main()
{
    B b;
    C c;
    c.init(b);

    c.doTask(0.5);
    return 0;
}

Compile g++ --std=c++11 test.cpp and I got:

/tmp/ccTmrVPi.o: In function `A::A()':
test.cpp:(.text._ZN1AC2Ev[_ZN1AC5Ev]+0x9): undefined reference to `vtable for A'
/tmp/ccTmrVPi.o: In function `std::_Head_base<0ul, A, false>::~_Head_base()':
test.cpp:(.text._ZNSt10_Head_baseILm0E1ALb0EED2Ev[_ZNSt10_Head_baseILm0E1ALb0EED5Ev]+0x14): undefined reference to `A::~A()'
/tmp/ccTmrVPi.o: In function `A::A(A const&)':
test.cpp:(.text._ZN1AC2ERKS_[_ZN1AC5ERKS_]+0xd): undefined reference to `vtable for A'
/tmp/ccTmrVPi.o: In function `B::~B()':
test.cpp:(.text._ZN1BD2Ev[_ZN1BD5Ev]+0x20): undefined reference to `A::~A()'
/tmp/ccTmrVPi.o:(.rodata._ZTI1B[_ZTI1B]+0x10): undefined reference to `typeinfo for A'
collect2: error: ld returned 1 exit status

0 Answers0