0

Why does my code below throw a compilation error complaining of undefined reference to Base::Base(), undefined reference to vtable for Derived and bad reloc address 0x0 in section '.ctors'. But when I define the constructor for Derived within the class, the compiler is able to compile the code.

#include <iostream>

class Base{
public: 
    Base();
    virtual ~Base();
};

class Derived : public Base{
public:
    Derived(double theob_);
    virtual ~Derived();
private: 
    double theob;
};

Derived::Derived(double theob_):theob(theob_){}

int main(){
    return 0;
}
user22119
  • 717
  • 1
  • 4
  • 18
  • see http://stackoverflow.com/questions/3065154/undefined-reference-to-vtable – nedR Feb 01 '14 at 09:08
  • What does it mean by defining the destructor? – user22119 Feb 01 '14 at 09:13
  • 1
    C and C++ make a difference between _declaration_, which is telling the compiler that a function exists and how it is called, and _definition_, where you write its body. In your code, **virtual ~Base();** is a declaration. A definition could look like **Base::~Base() { }** – Thomas Padron-McCarthy Feb 01 '14 at 09:19

2 Answers2

4

Your compilation unit declares Base::Base() but does not define it. Your derived constructor outside the body of the class is implemented as a non-inlined function, and as such will always be generated, and will reference that constructor which isn't included in the compilation unit. If you include the derived constructor in the class description, it will become inlined, and the compiler will only generate code for it if it is actually invoked. Which in your case it is not, since you never construct an instance of Derived. If you were actually constructing such an instance, e.g. by writing Derived d; inside main, you'd have the same problem. You could make Base::Base an inline no-op:

class Base{
public: 
    Base() {}
    virtual ~Base();
};
MvG
  • 57,380
  • 22
  • 148
  • 276
0

When you define the constructor within its class you make the constructor an inline method. So it will not be instantiated until it required - i.e until you have not declare a variable of the class.
Try this:

int main(){
    Derived var(0.0);
    return 0;
}

you will get the very same error.

KonstantinL
  • 667
  • 1
  • 8
  • 20