Some Examples
A class encapsulates data and functions both and manipulating them within a single unit. That can be additionally used as an abstract
<iostream.h>
const int max_items = 25;
class bag
{
private :
int contents[max_items];
int itemcount
public :
// sets itemcount to empty
void setempty()
{
itemcount=0;
}
void put(int item)
{
contents[itemcount++]=item;
}
void show();
};
// display contents of a bag
void bag::show()
{
for(int i=0;i<itemcount;i++)
cout << contents[i] <<" ";
cout << endl;
}
void main()
{
int item;
bag b1;
b1.setempty();// set bag to empty while (1)
{
cout << "Enter item number <0-no item>:";
cin >> item;
if (item == 0) // items ends, break break;
b1.put(item);
cout << "Items in bag :";
b1.show();
}
}
Run
Enter item number <0-no item>: 1
Items in bag : 1
Enter item number <0-no item>: 3
Items in bag : 1 3
Enter item number <0-no item>: 2
Items in bag : 1 3 2
Enter item number <0-no item>: 4
Items in bag : 1 3 2 4
Enter item number <0-no item>: 0
Within main() function, the statement bag b1;
creates the object bag without initializing the itemcount to 0 automatically. Moreover, that is performed through a call to the function setempty() as follows:
bag.setempty(); // set bag to empty
According to the philosophy of Object Oriented Programming's, whenever a new object like bag is created, that object will naturally be empty. For giving such a behavior in the program, it is must to invoke the member function setempty explicitly. Within reality, when a bag is purchased, it may holds some items placed inside the bag as gift items. Like a condition in C++ language could be simulated through
Bag b1 = 2;
That object creates the object bag and initializes it along with 2, denoting in which the bag is sold along with two gift items. That resembles the procedure of initialization of a built-in data type during creation, that is, there must be a provision in C++ to initialize objects in during creation itself.
It is thus clear in which OOPs must gives a support for initializing objects whenever they are created and destroy them when they are no longer required. Thus, a class in C++ might holds two special member functions dealing with the internal workings of a class. These functions are known as the constructors and the destructors. A constructor allows an object to initialize itself in during creation and the destructor destroys the object when it is no longer required, through releasing all the resources allocated to it. These operations are known as object initialization and clean up respectively.