Life cycle of Objects in C++ with Example
Last Updated :
04 Aug, 2021
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.
Below is the program for how constructor and destructors work in C++:
C++
// C++ program to demonstrate the
// object allocation & deallocation
#include <iostream>
using namespace std;
class object {
public:
// Constructor
object()
{
// Constructor has same name
// as that of class name
cout << "The object is created"
<< "\n";
}
// Destructor
~object()
{
// Destructor has same name as
// class and is preceded by ~ sign
cout << "The object is destructed"
<< "\n";
}
};
// Driver Code
int main()
{
// Object creation
object obj1;
return 0;
}
Output: The object is created
The object is destructed
When multiple objects are involved:
When multiple objects are created from the same class, the construction of the objects takes place in the same way they are created. However, the destruction follows LIFO(Last In First Out) approach i.e., the object which was created first will be destructed last. Since, when working with a single class, every new object is independent of the previous one so the order of destruction doesn't matter much. However, while working with inheritance, this LIFO order does make sense.
Below is the program to illustrate the same:
C++
// C++ program to illustrate the
// constructor and destructor when
// multiple objects are created
#include <iostream>
using namespace std;
// obj Class
class obj {
public:
// Declare class variable to
// keep count on objects
static int obj_count;
// Constructor
obj()
{
obj_count++;
cout << "The obj - "
<< obj_count
<< " - is created"
<< "\n";
}
// Destructor
~obj()
{
cout << "The obj - "
<< obj_count
<< " - is destructed"
<< "\n";
obj_count--;
}
};
// Static members are always defined
// outside of the class
int obj::obj_count = 0;
// Driver Code
int main()
{
// Creating objects
obj obj1{};
obj obj2{};
return 0;
}
Output: The obj - 1 - is created
The obj - 2 - is created
The obj - 2 - is destructed
The obj - 1 - is destructed
Behavior of object construction and destruction in case of inheritance:
Inheritance in C++ follows a IS-A approach. When a class B, inherits a class A, we say B IS-A. We say class B as derived class and class A as base class. Along with state and behaviors, class B also inherits constructor and destructor of the class A. There are some rules guiding inheritance of constructor and destructor.
- Derived class can not override or overload constructor and destructor of base class.
- The construction of base class takes place first, followed by the construction of derived class.
- The destruction of derived class takes place first.
Below is the program to illustrate the same:
C++
// C++ program to demonstrates the
// object Allocation and deallocation
// during inheritance B stands for base
// class and D stands for derived class
#include <iostream>
using namespace std;
// Class B
class B {
public:
// Constructor
B(int b = 0)
: _b(b)
{
cout << "constructor of base class "
<< "created with value - "
<< _b << '\n';
}
// Destructor
~B()
{
cout << "Destructor of base class "
<< "called \n";
}
int _b;
};
// Inherit class D from class B
class D : public B {
public:
D(int d)
: _d(d)
{
// Default constructor of b
// Is called automatically
cout << "constructor of derived "
<< " class created with value - "
<< _d << '\n';
}
// Overloaded Constructor
D(int b, int d)
: B(b), _d(d)
{
cout << "constructor of derived class "
<< "created with value - "
<< _d << '\n';
}
// Destructor
~D()
{
cout << "Destructor of derived class "
<< "called \n";
}
private:
int _d;
};
// Driver Code
int main()
{
// Object of class B
B b(34);
// Objects of class D
D d2(89);
D d1(56, 78);
return 0;
}
Output:
constructor of base class created with value - 34
constructor of base class created with value - 0
constructor of derived class created with value - 89
constructor of base class created with value - 56
constructor of derived class created with value - 78
Destructor of derived class called
Destructor of base class called
Destructor of derived class called
Destructor of base class called
Destructor of base class called
Why LIFO approach is used during object destruction?
Since the child class is inheriting states and behaviors from the parent class, so it makes sense that first all the work of child class should be finished and then only the object of the base class must be destroyed. Suppose, child class accesses a state from parent class but the parent object has been destructed, in this case, an error would occur and hence LIFO order is followed in destruction. This goes well even while working with multiple objects of single class.
Similar Reads
Mutual friendship of Classes in C++ with Examples
Prerequisite: Friend Class in C++A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private members of another class. Below is the program to illustrate the friend class: CPP // C+
4 min read
Deletion of array of objects in C++
Need for deletion of the object: To avoid memory leak as when an object is created dynamically using new, it occupies memory in the Heap Section.If objects are not deleted explicitly then the program will crash during runtime. Program 1: Create an object of the class which is created dynamically usi
3 min read
Exception Header in C++ With Examples
C++ provides a list of standard exceptions defined in header <exception> in namespace std where "exception" is the base class for all standard exceptions. All exceptions like bad_alloc, bad_cast, runtime_error, etc generated by the standard library inherit from std::exception. Therefore, all s
5 min read
Dynamic initialization of object in C++
In this article, we will discuss the Dynamic initialization of objects using Dynamic Constructors. Dynamic initialization of object refers to initializing the objects at a run time i.e., the initial value of an object is provided during run time.It can be achieved by using constructors and by passin
4 min read
Comparator Class in C++ with Examples
Comparator Classes are used to compare the objects of user-defined classes. In order to develop a generic function use template, and in order to make the function more generic use containers, so that comparisons between data can be made. Syntax cpp class comparator_class { public: // Comparator func
5 min read
Object Delegation in C++
Introduction: Every programming language that is based on an object-oriented concept tries to connect everything to the real world.Similarly, C++ languages use classes, Inheritance, Polymorphism to connect the concept with the real-world concept.In this article, the topic of discussion will be what
2 min read
C++ Exercises - C++ Practice Set with Solutions
Do you want to improve your command on C++ language? Explore our vast library of C++ exercise questions, which are specifically designed for beginners as well as for advanced programmers. We provide a large selection of coding exercises that cover every important topic, including classes, objects, a
15+ min read
How to Find the Type of an Object in C++?
In C++, every variable and object has a type. The type of an object determines the set of values it can have and what operations can be performed on it. Itâs often useful to be able to determine the type of an object at runtime, especially when dealing with complex codebases. In this article, we wil
2 min read
How to Use Deleted Functions to Prevent Object Copying in C++?
In C++, the class always has a copy constructor and assignment operator, whether it is default or user-defined which allows the program to create copies of the objects of that class. But sometimes, we need to create a class whose object should not be copied. In this article, we will learn how to use
2 min read
How to Create a Class with Private and Public Members in C++?
In C++, the classes are blueprints for creating objects with specific properties and methods that provide a feature of access specifiers to the user through which they can control the access of the data members present in a class. In this article, we will learn how to create a class with private and
3 min read