Introduction
This article will have an overview of C++ objects and destructors. Later on, we will discuss one of the essential and most asked topics, i.e. how the exceptions are handled using constructors.
Exception handling in C++ is vital because it helps to preserve the program's usual, desired flow even when unexpected occurrences occur. Programs may crash or requests may fail if exceptions are not handled appropriately. Customers may become irritated as a result, and a company's reputation may suffer as a result.
Here in this article, initially, we will have a revision on some basic topics of C++ related to OOPs. Later on, we learn about object destruction and exception handling in detail with the help of examples.
Also see, Literals in C.Fibonacci Series in C++
Basics of Object-Oriented Programming in C++
Before starting, let's have a peek at C++ objects, constructors & destructors, and exceptions:
- C++ object: An instance of the class with the same name as the class is an object.
- Constructor: A constructor is a member function that is automatically called when an object is formed. A constructor in C++ has the same name as the class and does not have a return type.
- Destructor: A destructor is a member function of a class with the same name as the class but preceded by a (tilde “~” ) symbol. It is also called automatically when the scope of the code expires. Object destruction is the activity of crushing or destroying existing object memory.
- C++ Exception: A C++ exception reacts to an unusual situation that occurs while a code is running, such as attempting to divide by zero. Exceptions allow us to move control from one portion of a program to another. Exception handling in C++ is based on three keywords: try, catch, and throw.
Note: A code in C++ never retains any form of memory or storage. It is the object that contains the memory or storage, and destructors are used to deallocate/destroy the memory of the produced object.