My code:
class A
{
public:
A(){}
A(int _a) : a(_a){}
virtual ~A() = 0;
private:
int a;
};
class B : public A
{
public:
B(){}
B(int _a):A(_a){}
~B(){}
private:
};
I declare B b;
, then when i compile this program, i met this error:
error LNK2019: unresolved external symbol "public: virtual __thiscall A::~A(void)" (??1A@@UAE@XZ) referenced in function "public: virtual __thiscall B::~B(void)" (??1B@@UAE@XZ)
I want to know, Do we need implement the pure virtual function all the time?
In general you do not need to implement a pure virtual function. Indeed that's sort of the point. However, with destructors you do, because it is not acceptable for a destructor to have no implementation. This is because unlike regular virtual methods, where only the most-derived one is used at runtime, all virtual destructors in an inheritance chain are called, from the most- to the least-derived, so that all fields of a derived object may be properly destroyed.
For this reason it may be preferable to not make pure your virtual destructors, except in cases where it is necessary (i.e. when you have a base class which must be abstract but which has no other virtual methods to be made pure).
You should implement it when it is invoked. otherwise not.
Pure virtual means that instance of a class that contains it coudnt be created, not that method coudn
t be called, nothing prevents you from calling pure virtual method from derived class in that case - implementation is needed.
Upd: in you case, as destructor of base class is invoked - implementation is needed, see explanation above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With