Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why we should implement pure virtual function in this case?

Tags:

c++

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?

like image 686
BlackMamba Avatar asked Dec 20 '22 02:12

BlackMamba


2 Answers

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).

like image 66
John Zwinck Avatar answered Feb 24 '23 16:02

John Zwinck


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 coudnt 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.

like image 31
spin_eight Avatar answered Feb 24 '23 15:02

spin_eight