In Object Oriented Programming, Objects are the instances of a class which has its own state(variables) and behavior(methods).
Every class has two special methods related with creation and destruction of object of a class- constructors and destructors.
C++ Object Life Cycle:
There are various steps that need to be followed to complete the life cycle of an object:
- First and foremost, some class is needed to define a class-based object. Therefore, an Example class is created in the above diagram.
- A constructor constructs values of the class type. It is a member function whose name is the same as the class name. This process involves initializing data members and, frequently, allocating free store using new.
- One can initialize the Example Object as created above. Initialization requires new keyword to be called, to allot some memory to this object.
- One can use some logic in the constructor, which will be executed during initialization.
- After execution is done, destructor is called. A destructor is a member function whose purpose is to destroy values of the class type. It is a member function whose name is preceded by the tilde(~) character.
- During this whole life cycle, remember the following facts:
- Constructors can be overloaded.
- A constructor is invoked when its associated type is used in a definition.
- Destructors are invoked implicitly when an object goes out of scope.
- Constructors and destructors do not have return types and cannot use return statements.
#c++ #constructors #destructors #cplusplus #programming-c