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

Constructor and Destructor Example in C++

C++ Constructor and Destructor Example

Constructors are for initialization. In the debugging and prototyping phase of code development, it is also useful to add code to constructors that outputs or tests behavior. However, once the debugging and prototyping phase is complete, any other work besides initialization should not be carried out by a constructor. For example, if in initializing an integer variable the system printed out its square root and whether it was prime, we would be properly upset.
Similarly, destructors are for deallocation and finalization. Other uses of destructors should be avoided. Destructors should retrieve resources connected with the variables going out of scope. They are conceptually the inverse computation to a corresponding constructor.

A constructor is a special kind of class member function that is executed when an object of that class is instantiated. Constructors are typically used to initialize member variables of the class to appropriate default values, or to allow the user to easily initialize those member variables to whatever values are desired. Unlike normal functions, constructors have specific rules for how they must be named:
  1. Constructors should always have the same name as the class (with the same capitalization)
  2. Constructors have no return type (not even void)

C++ also includes the ability to define a structure that is similar to a class and defines a type. The structure originated in C. You define a structure in essentially the same way as a class but using the struct keyword instead of the class keyword. In contrast to members of a class, the members of a structure are public by default. Structures are still used frequently in C++ programs to define types that represent simple aggregates of several variables of different types, the margin sizes and dimensions of a printed page for example. I will not discuss structures as a separate topic because aside from the default access specification and the use of the struct keyword, you define a structure in exactly the same way as a class.

Here is an example of a stack class with both a constructor and a destructor:
class ch_stack {
public:
  //constructor
  ch_stack(int size) { 
    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.