简体   繁体   中英

Why constructor for derived class can only be defined in-class for C++?

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;
}

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, eg 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();
};

When you define the constructor within its class you make the constructor an inline method. So it will not be instantiated until it required - ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM