Discuss construction and destruction of an object. Write a program to show the various phases of a simple base class in C++.


Q.) Discuss construction and destruction of an object. Write a program to show the various phases of a simple base class in C++.

Subject: Object Oriented Programming and Methodology

Construction and Destruction of an Object

Construction

  • An object is created by calling its constructor.
  • The constructor is a special member function of a class that has the same name as the class.
  • It is automatically called when an object is created.
  • The constructor initializes the data members of the object.

Destruction

  • An object is destroyed by calling its destructor.
  • The destructor is a special member function of a class that has the same name as the class, preceded by a tilde (~).
  • It is automatically called when an object is destroyed.
  • The destructor releases the resources used by the object.

Program to Show the Various Phases of a Simple Base Class in C++

#include 

using namespace std;

class Base
{
public:
  Base()
  {
    cout << "Base constructor called." << endl;
  }

  ~Base()
  {
    cout << "Base destructor called." << endl;
  }
};

int main()
{
  Base obj;

  return 0;
}

Output:

Base constructor called.
Base destructor called.

In this program, the constructor and destructor of the Base class are called when the object obj is created and destroyed, respectively.

The output of the program shows that the constructor is called before the destructor. This is because the constructor is called when the object is created, and the destructor is called when the object is destroyed.

Phases of a Simple Base Class in C++

The following are the various phases of a simple base class in C++:

  1. Declaration: The class is declared using the class keyword.
  2. Definition: The class is defined by providing its members, such as data members and member functions.
  3. Instantiation: An object of the class is created by calling its constructor.
  4. Usage: The object can be used to access its data members and member functions.
  5. Destruction: The object is destroyed by calling its destructor.

The following diagram shows the phases of a simple base class in C++:

[Diagram of the phases of a simple base class in C++]

Conclusion

Construction and destruction are important concepts in C++. Constructors are used to initialize objects, and destructors are used to release the resources used by objects. By understanding the various phases of a simple base class, you can write C++ programs that are efficient and reliable.