OOPortal OOPortal


Constructor Functions  «Prev  Next»
Lesson 5 Constructor and destructor example
Objective Class that uses simple constructor/simple destructor.

Constructor and Destructor Example in C++

Constructor Initialization
Here is an example of a stack class with both a constructor and a destructor:
class ch_stack {
public:
    ch_stack(int size)  //constructor
      { s = new char[size]; assert (s); } 
    ~ch_stack() { delete []s; }   //destructor
   . . . 
private:
   enum   { EMPTY = -1 };
   char*  s;
   int    max_len;
   int    top;
};

Constructors and destructors do not have return types, and cannot use return (expression) statements.
For the rest of this module, we will look at constructors. Destructors will be covered in more detail later.

A Counter Example

As an example, we will create a class of objects that might be useful as a general-purpose programming element. A counter is a variable that counts things. Maybe it counts file accesses, or the number of times the user presses the Enter key, or the number of customers entering a bank. Each time such an event takes place, the counter is incremented (1 is added to it). The counter can also be accessed to find the current count. Let us assume that this counter is important in the program and must be accessed by many different functions. In procedural languages such as C, a counter would probably be implemented as a global variable. Global variables complicate the program's design and may be modified accidentally. This example, COUNTER, provides a counter variable that can be modified only through its member functions.
// counter.cpp
// object represents a counter variable
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Counter
{
 private:
 unsigned int count; //count
 public:
  Counter() : count(0) //constructor{ /*empty body*/ }
  void inc_count(){ 
   count++; 
  }
  int get_count(){ 
   return count; 
  }
};
////////////////////////////////////////////////////////////////

int main()
{
 Counter c1, c2; //define and initialize 
 cout << “\nc1=” << c1.get_count(); //display
 cout << “\nc2=” << c2.get_count();
 c1.inc_count(); //increment c1
 c2.inc_count(); //increment c2
 c2.inc_count(); //increment c2
 cout << “\nc1=” << c1.get_count(); //display again
 cout << “\nc2=” << c2.get_count();
 cout << endl;
 return 0;
}

The Counter class has one data member: count, of type unsigned int (since the count is always positive). It has three member functions: the constructor Counter(), inc_count(), which adds 1 to count; and get_count(), which returns the current value of count.