Assignment Constructor
Assignment Constructor
1
CONSTRUCTOR:
A constructor is a member function of a class that has the same name as the class
name. It helps to initialize the object of a class. It can either accept the arguments
or not. It is used to allocate the memory to an object of the class. It is called
whenever an instance of the class is created. It can be defined manually with
arguments or without arguments. There can be many constructors in a class. It can
be overloaded but it cannot be inherited or virtual. There is a concept of copy
constructor which is used to initialize an object from another object.
Syntax:
DESTRUCTOR:
Like a constructor, Destructor is also a member function of a class that has the
same name as the class name preceded by a tilde (~) operator. It helps to deallocate
the memory of an object. It is called while the object of the class is freed or
deleted. In a class, there is always a single destructor without any parameters so it
can’t be overloaded. It is always called in the reverse order of the constructor. if a
class is inherited by another class and both the classes have a destructor then the
destructor of the child class is called first, followed by the destructor of the parent
or base class.
Syntax:
If we do not specify any access modifiers for the members inside the class then by
default the access modifier for the members will be Private.
Example/Implementation of Constructor and Destructor:
2
C++
OUTPUT:
3
NOW USING PYTHON LANGUAGE.
- The `__init__()` method is the constructor used for initializing the object. It takes
at least one argument (`self`) which refers to the instance of the class being created,
along with any other arguments needed for initialization.
- The `__del__()` method is the destructor used for finalizing or cleaning up the
object. It does not need to be explicitly called as Python's garbage collector
automatically takes care of memory management.
When you run the code, you will see the OUTPUT:
4
DIFFERENCE BETWEEN CONSTRUCTOR AND DESTRUCTOR :
S.
No. Constructor Destructor
5
S.
No. Constructor Destructor
They are often called in successive They are often called in reverse
10.
order. order of constructor.
6
• Easy to use: Destructors are easy to implement in Python, and can be
defined using the __del__ () method.
• Helps with debugging: Destructors can be useful for debugging, as they can
be used to trace the lifecycle of an object and determine when it is being
destroyed.
Destructors are an important feature of Python and can help to ensure that objects
are properly cleaned up and resources are not wasted. They are easy to use and can
be useful for enforcing encapsulation and other principles of object-oriented design