In Object Oriented ProgrammingObjects 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:

  1. First and foremost, some class is needed to define a class-based object. Therefore, an Example class is created in the above diagram.
  2. 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.
  3. One can initialize the Example Object as created above. Initialization requires new keyword to be called, to allot some memory to this object.
  4. One can use some logic in the constructor, which will be executed during initialization.
  5. 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.
  6. 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

Life cycle of Objects in C++ with Example
6.40 GEEK