c++11 - Linker refers to, supposedly, undefined reference to vtable -
i trying use abstract class represent common base subtypes. however, (the linker seems) keeps moaning vtables , undefined references no matter do. judging error messages, problem must related destructors in way. wierdldy enough, keeps talking a
"undefined reference 'abstractbase::~abstractbase()'"
in child.cpp makes no sense.
like last time, can't show code, here example in essence same thing:
first abstract class, "abstractbase.h":
#ifndef abstractbase #define abstractbase class abstractbase { public: virtual ~abstractbase() = 0; } #endif
the child uses abstractbase, "child.h":
#ifndef child #define child class child : public abstractbase { public: ~child() override; } #endif
the implementation in "child.cpp":
#include "child.h" child::~child()
obviously there far more functions, in essence that's how real class's destructors look.
after scouring web ways of using abstract classes in c++, give up. far can tell sources, way it. declare abstracts class's destructor virtual, call include child. , child's destructor marked override. there shouldn't else it.
have missed fundamental here?
ps: added mcve:
class abstractbase { public: virtual ~abstractbase() = 0; }; class child : public abstractbase { public: void dostuff() { //stuff } ~child() override {} } int main (argc, char *argv[]) { child* ptr = new child(); ptr->dostuff(); }
i should add errors not entirely identical, while original ones this:
undefined reference 'vtable abstractbase': in function abstractbase:~abstractbase()': undefined reference 'vtable abstractbase': undefined reference 'typeinfo abstractbase': collect2:error:ld returned 1 exit status
you need define destructor every class, otherwise cannot destroy objects of class (which includes member objects , base sub-objects):
class abstractbase { public: virtual ~abstractbase() = default; }; // ^^^^^^^^^^^
some alternative formulations:
user-defined:
struct abstractbase { virtual ~abstractbase() {} };
pure-virtual, defined:
struct abstractbase { virtual ~abstractbase() = 0; }; abstractbase::~abstractbase() = default;
this has benefit of leaving class abstract if have no other virtual member functions.
combine two:
struct abstractbase { virtual ~abstractbase() = 0; }; abstractbase::~abstractbase() {}
Comments
Post a Comment