answersLogoWhite

0


Best Answer

A destructor is not a function per-se. Functions have returns values but destructors do not (not even void). However, other than the lack of a return value, a destructor's body is no different to a function body.

Contrary to belief, destructors are not required by every class of object. Destructors are only required when we need to explicitly release a resource when an object of the class falls from scope, but not all resources need to be released explicitly. Consider the following class:

struct point {

int x, y;

};

This class does not require a destructor because it is self-contained. That is, all the resources consumed by an object of the class are contained within the object itself, thus when the object falls from scope, the memory it consumed is automatically released. There is nothing to destroy.

Now consider the following class:

class my_vector {

std::vector<int> v;

};

Again, this class requires no destructor. When objects of this class fall from scope, the vector's destructor is invoked, releasing its resources. Thus the only resource consumed by this class is the vector itself, and that's self-contained by the class.

Now let's consider a class that does require a destructor:

template<typename T>

class smart_pointer {

T* ptr;

// ...

};

Here, we have a class that encapsulates a "naked" pointer variable of some type T. That pointer could feasibly refer to any object of type T in memory. However, being a "smart pointer", the assumption is that objects of this class will "own" the memory they refer to. As the owner, it makes sense to yield ownership whenever object's of the class fall from scope. If we didn't provide a destructor, ptr would fall from scope, but the memory it referred to would not. So to ensure the memory is released, we must explicitly release it via the class destructor:

template<typename T> class smart_pointer {

T* ptr;

// ...

public:

~smart_pointer () { delete ptr; }

};

To summarise: a destructor is only required when an object acquires a non-shared resource that is not released automatically when objects of the class fall from scope. A vector is a resource handle, so when it falls from scope, its resources are released automatically. Similarly with smart pointers. However a "naked" pointer is not a resource handle, so if our class "owns" a resource by holding a pointer to it, then we must release that pointer when objects of the class are destroyed. Resources cover many things besides raw memory. If we hold a reference to an open file, it would be prudent to close the file before the reference falls from scope. With a resource handle we get that assurance. Thus if we use resource handles rather than "raw" resources, then we need never write any destructors.

There can be other reasons to require a destructor besides resource management, such as to write an entry in a log file upon destruction, however resource management and other "housekeeping" task are not a requirement of every class thus a destructor is not required by every class.

User Avatar

Wiki User

7y ago
This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: Why is a destructor function required in C plus plus classes?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

How do you implement inheritance in c plus plus?

You implement inheritance by deriving a new class of object from an existing class of object. The existing class is known as the base class of the derived class.Classes declared final cannot be used as bases classes and classes without a virtual destructor (or a virtual destructor override) cannot be used as polymorphic base classes.


How do you use delete function in inheritence in classes using c plus plus?

You use delete to release the memory occupied by an object that is being pointed to by the pointer you delete. Provided all base classes have a virtual destructor, it doesn't matter what the type of pointer you actually delete is, so long as it is a type of class from which the object is actually derived. The destructor from the most-inherited class (the object itself) will be called first, which calls the destructors of its immediate base classes, and theirs, and so on until the object is completely released from memory.Note that you must not delete pointers to object references -- they must be nullified (not deleted) when they are no longer required. The referenced object will be deleted automatically when it falls from scope.


When destructor can be virtual in c plus plus?

A class constructor initialises object member variables, ensuring the object is in a valid state from the point of instantiation. The destructor resets those same variables when the object falls from scope. Typically, the destructor is only required to release any memory allocated to any internal class pointers.


What is the difference between destructors in c plus plus and c sharp?

In C# only class instances can have a destructor, whereas both class and struct instances can have a destructor in C++. While syntactically similar, a C++ destructor executes exactly as written, whereas a C# destructor merely provides the body of the try clause of the class' finalize method.


What is a primary function in C plus plus?

There is no such thing. You probably meant the main function. The main function is the only function that is required as it serves as the entry point of the program.

Related questions

How do you implement inheritance in c plus plus?

You implement inheritance by deriving a new class of object from an existing class of object. The existing class is known as the base class of the derived class.Classes declared final cannot be used as bases classes and classes without a virtual destructor (or a virtual destructor override) cannot be used as polymorphic base classes.


How do you use delete function in inheritence in classes using c plus plus?

You use delete to release the memory occupied by an object that is being pointed to by the pointer you delete. Provided all base classes have a virtual destructor, it doesn't matter what the type of pointer you actually delete is, so long as it is a type of class from which the object is actually derived. The destructor from the most-inherited class (the object itself) will be called first, which calls the destructors of its immediate base classes, and theirs, and so on until the object is completely released from memory.Note that you must not delete pointers to object references -- they must be nullified (not deleted) when they are no longer required. The referenced object will be deleted automatically when it falls from scope.


When destructor can be virtual in c plus plus?

A class constructor initialises object member variables, ensuring the object is in a valid state from the point of instantiation. The destructor resets those same variables when the object falls from scope. Typically, the destructor is only required to release any memory allocated to any internal class pointers.


What is the difference between destructors in c plus plus and c sharp?

In C# only class instances can have a destructor, whereas both class and struct instances can have a destructor in C++. While syntactically similar, a C++ destructor executes exactly as written, whereas a C# destructor merely provides the body of the try clause of the class' finalize method.


What is a distructor in c plus plus?

A destructor destroys an instance of a class to free up memory.


What is a primary function in C plus plus?

There is no such thing. You probably meant the main function. The main function is the only function that is required as it serves as the entry point of the program.


What is the order of construction and destruction in c plus plus?

The least-derived base classes are always constructed first, in the order specified by the derived class inheritance list. The most-derived class (the one you are actually instantiating) is always constructed last. Destruction is basically the reverse of construction. However, base class destructors must be declared virtual to ensure that the most-derived class destructor is called first, regardless of which class destructor is actually invoked. That is, if you hold a pointer to a base class that has no virtual destructor, deleting that pointer will only destroy the base class, not the derived class, leaving the derived class in an invalid state (because it no longer has an underlying base class) and with no way to recover the memory it consumes. It is important to remember that if you declare any virtual methods within a class, you must also declare the destructor virtual. A class without a virtual destructor is not intended to be derived from. If it has virtual methods, but no virtual destructor, it is not well-formed and must not be used as a base class.


How do you write a C plus plus program for destructor?

Class destructors define operations that will be performed whenever an object of the class falls from scope. This usually involves manually releasing any resources allocated to the object. However, by using resource handles or smart pointers, all resources will be released automatically, thus there is no need to define a destructor. The only time we really need to define a destructor is when the class is intended to be used as a polymorphic base class (has one or more virtual methods) but does not inherit a virtual destructor, in which case we must define a virtual destructor. Classes that do define or inherit a virtual destructor cannot be used polymorphically. However, by using resource handles or smart pointers to manage resources, the destructor body can be left empty. The only reason for declaring the destructor at all is simply to declare it virtual because all methods are non-virtual by default -- unless they override a virtual method of the base class (in which case they can simply be declared as overrides). The only time we need to define a non-empty destructor body is when implementing a resource handle or smart pointers, however the standard library already provides efficient implementations so, other than for educational purposes, there is no need to define our own resource handles.


What is a Generic Function in c plus plus?

Predefined functions are built-in functions that perform standard operations and that generally do not depend on any classes. A predefined void function is simply a predefined function that has no return value. An example of a predefined void function is the abort() function which typically has the following signature: void abort(void);


Why constructers can not be inherrited in c plus plus?

Every class of object must provide its own specific construction code. Since they are not really functions they cannot be overridden, thus they cannot be inherited. The same applies to the class destructor and the class self-assignment operator. Each class must handle these explicitly, within the class implementation. They cannot be implemented outside of the class, and therefore cannot be inherited. Although the virtual keyword can be applied to the destructor, it's not a function and therefore not a virtual function. The only reason for having a virtual destructor at all is when one or more of the class methods are virtual. Since classes with virtual methods are intended to act as generic interfaces for more specialised implementations, it's important that when destroying such a class that the most-derived (or most-specialised) class is destroyed first, working up the hierarchy to the base class which must always be destroyed last. This can only be achieved through virtual destruction. Failure to declare the base class destructor virtual could result in a base class being destroyed (such as when deleting a pointer to it), which would then result in an incomplete and therefore invalid derived class remaining in memory.


How can you justify the use of constructor and destructor in c plus plus?

Constructors allow class designers to initialise class attributes at the point of instantiation (whenever an object of the class is created). All classes must have at least one constructor other than the copy and move constructors otherwise it would be impossible to instantiate objects of the class. Copy and move constructors are not required but are generated automatically by the compiler unless the class designer explicitly marks them deleted from the class definition. The copy and move constructors allow new instances to be constructed from existing instances. The only difference between the two is that the move constructor transfers ownership of the member attributes, rather than merely copying them. In classes that contain pointers, the compiler-generated copy constructor only copies the pointer (a shallow copy) not what it points at (a deep copy). Thus class designers must provide a copy constructor in order to deep copy any unshared memory resources. Derived class constructors automatically invoke base class constructors, so classes are always constructed from the bottom up. Copy and move constructors automatically invoke their base class copy and move constructors, respectively, however all other constructors automatically invoke their base class default constructors, which may not be the most efficient method of construction. Thus class designers can invoke specific base class constructors through the constructor's own initialisation list (which is also used to initialise member attributes). Constructor bodies do not require any code except in those cases where initialisation is not possible with the initialisation list alone, however this is usually an indication of poor design choices rather than a limitation of the initialisation list. The initialisation list provides the most efficient mechanism for class initialisation. Every class must have one (and only one) destructor. If one is not provided by the class designer, the compiler generates one for you. However, unless the class contains a pointer to unshared memory, there is no need to define your own. Otherwise you must provide a destructor in order to release the memory. The destructor is the last chance to do so before an object of the class falls from scope. Classes that are intended to act as base classes must provide a virtual destructor (that is, the lowest base class must declared the destructor virtual). This ensures that if an object is destroyed polymorphically (via a pointer to one of its base classes), the most-derived destructor is always invoked first. Destruction of hierarchies is always top down. Note that destructors are not virtual by default for the simple reason that not all classes are intended to act as base classes. The containers provided by the Standard Template Library (STL) are a good example of this as none of the containers have virtual destructors -- so they cannot be used as base classes. Note that if any class method is declared virtual, the destructor must also be declared virtual. However, when inheriting from a base class with a virtual destructor, the class destructor is implicitly virtual (as are all virtual functions inherited from base classes) and does not need to be specified, although its good practice to explicitly include it anyway.


What are the advantages of having program in a class in C plus plus?

You don't write programs in a class in C++, you write programs that use classes. Every C++ has at least one function, main, the entry point of the application. You define the classes and functions that are used by your main function. Classes allow you to classify the objects used by your program, allowing data to be manipulated in a highly controlled manner, ensuring consistency and robustness throughout your program.