OOPS
Destructor
● A destructor is also a special member function like a constructor.
Destructor destroys the class objects created by the constructor.
● Destructor has the same name as their class name preceded by a
tilde (~) symbol.
● It is not possible to define more than one destructor.
● The destructor is only one way to destroy the object created by the
constructor. Hence destructor can-not be overloaded.
● Destructor neither requires any argument nor returns any value.
● It is automatically called when an object goes out of scope.
● Destructor release memory space occupied by the objects created
by the constructor.
● In destructor, objects are destroyed in the reverse of an object
creation.
● It cannot be declared static or const.
● An object of a class with a Destructor cannot become a member of the
union.
● A destructor should be declared in the public section of the class.
● The programmer cannot access the address of the destructor.
The thing is to be noted here if the object is created by using new or the
constructor uses new to allocate memory that resides in the heap memory or
the free store, the destructor should use delete to free the memory.
When is the destructor called?
A destructor function is called automatically when the object goes out of
scope:
1. the function ends
2. the program ends
3. a block containing local variables ends
4. a delete operator is called
Note: destructor can also be called explicitly for an object.
When do we need to write a user-defined destructor?
If we do not write our own destructor in class, the compiler creates a default
destructor for us. The default destructor works fine unless we have
dynamically allocated memory or pointer in class. When a class contains a
pointer to memory allocated in the class, we should write a destructor to
release memory before the class instance is destroyed. This must be done to
avoid memory leaks.
Virtual destructor : - Deleting a derived class object using a pointer of base
class type that has a non-virtual destructor results in undefined behavior. To
correct this situation, the base class should be defined with a virtual
destructor.
Copy constructor makes a new memory storage every time it is called while
the assignment operator does not make new memory storage.
Copy constructor Assignment operator
It is called when a new object is This operator is called when an
created from an existing object, as already initialized object is
a copy of the existing object assigned a new value from another
existing object.
It does not create a separate
It creates a separate memory
memory block or new memory
block for the new object.
space.
It is an overloaded constructor. It is a bitwise operator.
C++ compiler implicitly provides a A bitwise copy gets created, if the
copy constructor, if no copy Assignment operator is not
constructor is defined in the class. overloaded.
Syntax: Syntax:
className(const className &obj) className obj1, obj2;
{
// body
obj2 = obj1;