c++inheritance

c++ Linker error undefined reference to vtable


I'm trying to write a small C++ inheritance program, that will contain virtual functions, headers, and 3 class, A, B:A, C:B, after compiling succeeds, the linker fails in the derived of a derived class, C.o, stating

relocation against `_ZTV26C' in read-only section `.text'

and

undefined reference to `vtable for C'

can anyone see what am i missing?

A.h

#ifndef A_H_
#define A_H_
#include <string>
#include <iostream>
using namespace std;

class A {
protected:
    string name;
public:
    A(string name);
    virtual ~A();
    virtual void justATest(){}
    void justBecause();
    virtual bool derivedTest(){}
};

#endif /* A_H_ */

A.cpp

#include "A.h"

A::A(string name) {this->name.assign(name);}

A::~A() {}

void A::justBecause(){}

B.h

#ifndef B_H_
#define B_H_
#include "A.h"
#include <string>

class B : public A{
public:
    B(string name):A(name){}
    virtual ~B(){}
    bool derivedTest();
};

#endif /* B_H_ */

B.cpp

#include "B.h"
bool B::derivedTest()
{
    return true;
}

C.h

#ifndef C_H_
#define C_H_
#include "B.h"

class C : public B{
public:
    C(string name) :B(name){}
    virtual ~C(){}
    void justATest();
};

#endif /* C_H_ */

C.cpp

#include "C.h"
void C::justATest()
{
    cout<< this->name;
}

main.cpp

#include "C.h"
int main(int argc, char* argv[]) {
    C* c = new C("str");
return 0;
}

the exact make command, and the error message: make all Building target: demo_proj Invoking: GCC C++ Linker g++ -o "ass5_demo" ./A.o ./B.o ./C.o ./main.o /usr/bin/ld: ./main.o: warning: relocation against _ZTV1C' in read-only section .text._ZN1CC2ENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE[_ZN1CC5ENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE]' /usr/bin/ld: ./main.o: in function C::C(std::__cxx11::basic_string<char, std::char_traits, std::allocator >)': /home/some_user/eclipse-workspace/demo_proj/../C.h:14: undefined reference to vtable for C' /usr/bin/ld: warning: creating DT_TEXTREL in a PIE


Solution

  • After many hours of debugging, and countless tries, with the same error message i found the answer. This is C++ linker crooked way of telling me there is an unimplemented method in one of my classes. adding to c.h

    bool derivedTest() override;
    

    and to c.cpp

    bool C::derivedTest(){return false;}
    

    p.s another nice way of finding the problem is adding override after each message in the header file, the compiler is much clearer