Why should we implement a pure virtual function in this case?

My code is:

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: }; 

Announcing 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 if we need to constantly perform a pure virtual function?

+4
source share
4 answers

In general, you do not need to implement a pure virtual function. In fact, such a point. However, with the destructors that you do, because the destructor is unacceptable for implementation. This is due to the fact that, unlike conventional virtual methods, in which only the most derivative is used at runtime, all virtual destructors in the inheritance chain are named from the smallest to the least derivative, so that all fields of the derived object can be correctly destroyed.

For this reason, it may be preferable not to clean your virtual destructors, unless it is necessary (i.e. when you have a base class that should be abstract, but that does not have other virtual methods that need to be made clean).

+9
source

You must implement it when calling it . otherwise no. A pure virtual means that an instance of the class that contains its coudn t be created, not that method coudn t will be called, nothing prevents you from t be created, not that method coudn pure virtual method from a derived class in this case - implementation is required .

Update: in your case, when the base class destructor is called, an implementation is required, see the explanation above.

+1
source

A pure virtual function must be implemented if called. So for example:

 struct A { virtual void f() = 0; }; struct B : A { void f(); }; void B::f() { std::cout << "B::f called\n"; } 

However, if B::f calls A::f , then A::f must be implemented:

 void B::f() { A::f(); std::cout << "B::f called\n"; } 

With this definition of B::f must also be a definition of A::f .

The same thing with a virtual destructor: if it called, it must be implemented. For the destructor, the difference is that the destructor in the base class is always called by the destructor for the derived class, so you should always implement a pure virtual destructor. Even if it does nothing.

+1
source

A pure virtual function is, by definition, a virtual function that must be constantly defined in an inherited object. So the answer is yes. If you really don't need it, you can simply define a function without code inside.

0
source

Source: https://habr.com/ru/post/1495736/


All Articles