2

What´s the wrong in this code?

template <class T>
class A
{
private:
    T a;

public:
    A(): a(0) {}
    virtual ~ A() = 0;
};


template <class T>
class A;

template <class T>
class B : public A<T>
{
private :
    T b;

public:
    B() : A<T>() {}
    virtual ~B(){}


};


int _tmain(int argc, _TCHAR* argv[])
{
B <double> bb;
return 0;
}

error LNK2019: unresolved external symbol "public: virtual __thiscall A::~A(void)" (??1?$A@N@@UAE@XZ) referenced in function "public: virtual __thiscall B::~B(void)" (??1?$B@N@@UAE@XZ)

Woody
  • 69
  • 2
  • 6

3 Answers3

9

You declare A's destructor as pure virtual. This is all well and good, and can be considered good practice if you want to guarantee the class is never instantiated. However, you must still define A::~A() somewhere in your code, as B's destructor automatically calls A::~A() on the B object. Since you declared it pure virtual, you cannot define it inline as you did with ~B; you must include it's definition outside the class definition.

Daniel Gallagher
  • 6,915
  • 25
  • 31
  • I believe it can be implemented inline in VC++. (That's not portable, but neither is `_tmain(int, _TCHAR *[])`.) – Fred Foo Jan 20 '11 at 20:13
  • I believe you can in GCC as well. However, I was trying to say that you cannot declare it pure virtual and implement it inline at the same time (unless you implement it inline after the class definition). – Daniel Gallagher Jan 20 '11 at 20:15
0

You need to provide implementation for base class destructor. Even if destructor is declared pure virtual, implementation is required to destroy derived classes.

Gene Bushuyev
  • 5,512
  • 20
  • 19
0

Your superclass destructor should not be pure virtual, just virtual.

virtual ~A() {}

The destructor of B will automatically try to call the destructor of A.

James
  • 5,355
  • 2
  • 18
  • 30
  • 1
    you should add the definition of the destructor, because the compiler need it when you let B inherits from the class A to build the descructor of B. Defining destructor A pure virtual is considered best practice by most. – fiorentinoing Nov 26 '18 at 09:31