virtual VS non virtual, how the destructor of C is defined

Mondo Technology Updated on 2024-02-02

virtual is a keyword in C++ that indicates that a method can be rewritten by a subclass, i.e. it can be redefined in a subclass. This allows polymorphism to be achieved by the way the base class pointer points to the subclass object. For example:

#include

class baseclass

baseclass(int x, int y) :ix(x), iy(y)

baseclass()

virtual void print()

protected:

int ix{};

int iy{};

class derivedclass : public baseclass

void print() override

derivedclass()

private:

int* iz;

int main()

When this modification is completed and executed, the output becomes.

base class default constructor.

derived class constructor.

derivedclass: 2 4 3

derivedclass destructor

base class destructor.

If there is an extra line marked in red, the destructor of the derived class will also be called, and the memory applied by the derived class will be released normally.

Now the problem is here again:If I change all the class destructors to virtual, is that the optimal solution?

The answer is no.

For a class, if it is not intended to be used for inheritance when it is defined, there must be no virtual method in the definition of the class, and if the destructor is defined as a virtual method, the class will add a virtual function table pointer in memory to point to the virtual function table of the class (please search for the introduction of the virtual function table). For a simple class, simply because you are lazy to define a virtual destructor for all classes that don't use virtual functions, and add a virtual function table pointer, it will often slow down the performance of the program!

Summary: If a class doesn't use any virtual functions, don't define the destructor as virtual.

Also, since C++ doesn't prohibit derivation (i.e. a class can always be used to inherit), be careful not to use inheritance when using non-virtual destructor classes!

Related Pages