Why is destructor virtual in c




















From cppreference. Keywords Escape sequences. Namespace declaration. Namespace aliases. Fundamental types Enumeration types Function types. Compound types Union types. Default initialization Value initialization Zero initialization Copy initialization Direct initialization. Expressions Value categories Order of evaluation.

Operators Operator precedence. Class declaration Constructors this pointer. Access specifiers friend specifier. Class template Function template. Inline assembly. Run this code. Compiler support. Freestanding and hosted.

Language support library. Technical specifications. Flow control. Function declaration. Lambda function declaration. Fundamental types. Function types. Compound types.

This is undesirable behaviour as the operating system has no mechanism to regain the lost memory because it does not have any references to its location! Since memory is a finite resource, if this leak persists over continued program usage, eventually there will be no available RAM random access memory to carry out other programs.

For instance, consider a pointer to a base class such as PayOff being assigned to a derived class object address via a reference. If the object that the pointer is pointing to is deleted, and the destructor is not set to virtual , then the base class destructor will be called instead of the derived class destructor. This can lead to a memory leak. Consider the following code:. What is happening here?

Firstly, we create a base class called Base and a subclass called Derived. The destructors are NOT set to virtual. When someone will delete a derived-class object via a base-class pointer. In particular, here's when you need to make your destructor virtual : if someone will derive from your class, and if someone will say new Derived , where Derived is derived from your class, and if someone will say delete p , where the actual object's type is Derived but the pointer p 's type is your class.

Here's a simplified rule of thumb that usually protects you and usually doesn't cost you anything: make your destructor virtual if your class has any virtual functions. Rationale: that usually protects you because most base classes have at least one virtual function. In other words, you've already paid all the per-object space-cost that you'll ever pay once you add the first virtual function, so the virtual destructor doesn't add any additional per-object space cost.

Angular 7. Machine Learning. Data Structures. Operating System. Computer Network. Compiler Design. Computer Organization. Discrete Mathematics. Ethical Hacking. Computer Graphics. Software Engineering.

Web Technology.



0コメント

  • 1000 / 1000