0

I'm getting the error undefined reference to 'vtable for Base'. I don't know what this means as I am not using anything called "vtable". Also, I don't exactly understand how making pointers and new Derived are affecting the program. Can anyone clear this up? Thanks.

#include <iostream>

using std::cout;

class Base { // undefined reference to 'vtable for Base'

    public:
        void f();
        virtual void bar();

};
class Derived : public Base {
    public:
        void f();
        void bar() {
            cout << "I am bar";
        }
};

int main() {

    Derived d;
    Base * b = &d;

    b->bar();

}
template boy
  • 10,230
  • 8
  • 61
  • 97

2 Answers2

4

You must implement virtual functions of classes you instantiate in order to compile. (or mark them pure virtual).

Just make bar empty in Base:

virtual void bar() {}

Or pure virtual (must be reimplemented in derived classes in order to instantiate them)

virtual void bar() = 0;
Andrew
  • 24,218
  • 13
  • 61
  • 90
  • Thanks. This works. I have a few questions though: When inheriting, what happens when you do `class Derived : Bar`, `class Derived public Bar`, `class Derived : protected Bar`, and `class Derived : private Bar`. Also, what does `new Derived` do? – template boy Aug 16 '12 at 13:13
  • 1
    @user6607: 1. http://stackoverflow.com/questions/860339/difference-between-private-public-and-protected-inheritance-in-c. 2. Allocating object on the heap. I suggest you to pick a c++ book – Andrew Aug 16 '12 at 13:16
  • @user6607 to answer those questions, search stackoverflow, and if you don't find answers, ask. But only one question at a time. – juanchopanza Aug 16 '12 at 13:17
1

You have two problems. First, make the methods in Base pure virtual:

class Base {
    public:
        virtual void f()=0;
        virtual void bar()=0;
};

Second, you need to implement f():

class Derived : public Base {
    public:
        void f(){}
        void bar() {}
};
juanchopanza
  • 223,364
  • 34
  • 402
  • 480