简体   繁体   中英

c++ inheritance issues: undefined reference to 'vtable'

all! I am trying to create a very simple inheritance structure using C++ and header files but (of course) I am having some difficulties.

When I try to compile my main program, I get this error:

In function `Base::Base()':
undefined reference to 'vtable for Base'
In function `Derived::Derived()':
undefined reference to 'vtable for Derived'

All I want is to print is

printed in Derived

but I am having some extreme difficulties.

Here are my program files:

main.cpp

#include <iostream>
#include "Base.h"
#include "Derived.h"

using namespace std;

int main(void) {
    Base *bp = new Derived;
    bp->show();
    return 0;
}

Base.cpp

#include <iostream>
#include "Base.h"

virtual void Base::show() {
    cout << "printed in Base";
}

Base.h

#ifndef BASE_H
#define BASE_H

class Base {
    public:
        virtual void show();
};

#endif

Derived.cpp

#include <iostream>
#include "Derived.h"

using namespace std;

void Derived::show() override {
    cout << "printed in Derived";
}

Derived.h

#ifndef DERIVED_H
#define DERIVED_H

class Derived: public Base {
    public:
        void show() override;
};

#endif

Thank you! And any help is very much appreciated!...extremely.

As pointed out in the comments, by calling g++ main.cpp you are only compiling main.cpp .

You need to compile all files, then link them together. If you do so, you will see that there are compilation issues in your other cpp files as also pointed out in the comments ( virtual and override only belong in the header ).

So you need to call the following to compile all files: g++ main.cpp Base.cpp Derived.cpp -o myapp

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