2

I have take code from cppfaq 12.15 and trying to compile but getting error in linux with gcc version 4.8.4.

undefined reference to `vtable for

I am surprise as I do not have any virtual method. I have looked into following question but not able figure out issue.

c++ undefined reference to vtable

Undefined reference to 'vtable for xxx'

The code

#include<iostream>
#include<new>
#include<memory> using namespace std;

class Fred; typedef auto_ptr<Fred> FredPtr;

class Fred {
    public:
        static FredPtr create() throw(bad_alloc);
        static FredPtr create(int i) throw(bad_alloc);
        static FredPtr create(const Fred& x) throw(bad_alloc);
        virtual void goBowling();
    private:
        Fred(int i=10);
        Fred(const Fred& x);
        int i_;
    };

FredPtr Fred::create() throw (bad_alloc) {   return auto_ptr<Fred>(new Fred()); }

FredPtr Fred::create(int i) throw(bad_alloc) {
    return auto_ptr<Fred>(new Fred(i)); }

FredPtr Fred::create(const Fred& x) throw(bad_alloc) {
    return auto_ptr<Fred>(new Fred(x)); }

Fred::Fred(int i) {
    i_ = i;
    cout<<" This is simple constructor"<<endl; }

Fred::Fred(const Fred& x) {
    i_ = x.i_;
    cout<<" This is copy constrcutor"<<endl; }

void sample() {
    FredPtr p(Fred::create(5));
    p->goBowling(); }

int main() {
    sample();
    return 0; }

Error:

/tmp/cc6JnLMO.o: In function `Fred::Fred(int)':
cpp12_15.cpp:(.text+0x204): undefined reference to `vtable for Fred'
/tmp/cc6JnLMO.o: In function `Fred::Fred(Fred const&)':
cpp12_15.cpp:(.text+0x247): undefined reference to `vtable for Fred'
collect2: error: ld returned 1 exit status 
9
  • 2
    cplusplus.com/reference/memory/auto_ptr - see the deprecated note Commented Jul 7, 2015 at 7:08
  • You should define a public: virtual ~Fred() {} destructor. Commented Jul 7, 2015 at 7:09
  • Usually this error means that you forgot to include the function body for some other function Commented Jul 7, 2015 at 7:09
  • 2
    Definition for void Fred::goBowling() {} is missing. Commented Jul 7, 2015 at 7:14
  • 3
    You say you have no virtual functions, yet you have virtual void goBowling();.... Commented Jul 7, 2015 at 7:14

1 Answer 1

3

As long as you have a virtual keyword in you class definition the compiler will build statically the vtable even if you're not inheriting from it, as you can see in your class you didn't define your goBowling method so compilation will fail.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.