Constructors and Destructors – C++ Source Code

The following C++ program demonstrates the concept of constructors and destructors in C++.

A constructor is a special method that is created when the object is created or defined. This particular method holds the same name as that of the object and it initializes the instance of the object whenever that object is created.

As opposed to a constructor, a destructor is called when a program has finished using an instance of an object. A destructor does the cleaning behind the scenes.

#include <iostream.h>

class rectangle {              // A simple class
   int height;
   int width;
public:
   rectangle(void);            // with a constuctor,
   int area(void);             // two methods,
   void initialize(int, int);
   ~rectangle(void);           // and a destructor
};


rectangle::rectangle(void)     // constuctor
{
   height = 6;
   width = 6;
}

int rectangle::area(void)      //Area of a rectangle
{
   return height * width;
}

void rectangle::initialize(int init_height, int init_width)
{
   height = init_height;
   width = init_width;
}

rectangle::~rectangle(void)    // destructor
{
   height = 0;
   width = 0;
}

struct pole {
   int length;
   int depth;
};


int main(void)
{
rectangle box, square;
pole flag_pole;

   cout << "The area of the box is " <<
                       box.area() << "\n";
   cout << "The area of the square is " <<
                       square.area() << "\n";

// box.height = 12;
// box.width = 10;
// square.height = square.width = 8;

   box.initialize(12, 10);
   square.initialize(8, 8);

   flag_pole.length = 50;
   flag_pole.depth = 6;

   cout << "The area of the box is " <<
                       box.area() << "\n";
   cout << "The area of the square is " <<
                       square.area() << "\n";

}

The output of the C++ Program

 The area of the box is 36
 The area of the square is 36
 The area of the box is 120
 The area of the square is 64

 

M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post