zhiar
zhiar

Reputation: 113

C++ derived class and virtual destructor

Please have a look at the simple code below:

#include <iostream>
using namespace std;

class semi_shape_1 {
public:
    void output() { cout <<" semi_shape_1 works fine.\n"; }
    virtual ~semi_shape_1();

protected:
    semi_shape_1(){ output();}
};

class test_semiShape_1 : public semi_shape_1 {
};


int main()
{
    test_semiShape_1 ts1;
    return 0;
}

The semi_shape_1 is a bass class and the test_semiShape_1 has been derived from it. When I run the code, I get two errors as follows:

Error1 error LNK2019: unresolved external symbol "public: virtual __thiscall semi_shape_1::~semi_shape_1(void)" (??1semi_shape_1@@UAE@XZ) referenced in function "public: virtual __thiscall test_semiShape_1::~test_semiShape_1(void)" (??1test_semiShape_1@@UAE@XZ) C:\Users\ME\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\ConsoleApplication1.obj

Error2 error LNK1120: 1 unresolved externals C:\Users\ME\Documents\Visual Studio 2012\Projects\ConsoleApplication1\Debug\ConsoleApplication1.exe 1

What is the problem with my code please?
Machine: Windows 7.
IDE: visual studio 2012.

Upvotes: 1

Views: 795

Answers (3)

JumpandSpintoWin
JumpandSpintoWin

Reputation: 187

There is no implementation of the base class's destructor. The compiler will implicitly create one if you do not provide a definition, but since you provided one, you must also provide the implementation. Tony's comment has the answer:

Just change virtual ~semi_shape_1(); to virtual ~semi_shape_1() { }

Upvotes: 2

Brian Bi
Brian Bi

Reputation: 119144

You have to provide a definition for the destructor.

virtual ~semi_shape_1() {}

or in C++11

virtual ~semi_shape_1() = default;

or you can make it pure if semi_shape_1 is supposed to be an abstract class, but don't forget to define it outside the class definition:

virtual ~semi_shape_1() = 0;
// ...
semi_shape_1::~semi_shape_1() = default;

Upvotes: 1

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145259

You have declared a destructor but not implemented it.

Upvotes: 0

Related Questions