Showing posts with label Object. Show all posts
Showing posts with label Object. Show all posts

Counting the Number of Objects of a Particular Class in a C++ Program

This program demonstrates how to count the number of objects that are created for a class in C++ at runtime. The idea is to have a variable that increments and counts everytime a new object has been created of a particular class. Therefore this program features what is known as the static type of variable of the class. A static variable is one that has only copy of itself no matter how many objects are created for that class. 

Create an Array of Objects in C++



This program shows you how to create an array of objects in C++. The class cl has two variables and two functions to retrieve the values of the two variables. It also has a constructor that is used to initialize the two variables in the parameters when the object is created. See code below:

Illustrate Object Arrays in C++


#include <iostream.h>
#include <conio.h>
class cl {
int h;
int i;
public:
cl(int j, int k) { h=j; i=k; } // constructor with 2 parameters
int get_i() {return i;}
int get_h() {return h;}
};

int main()
{
      clrscr();
      cl ob[3] = {
      cl(1, 2), // initialize
      cl(3, 4),
      cl(5, 6)
};

      int i;

for(i=0; i<3; i++)
 {
      cout << ob[i].get_h();
      cout << ", ";
      cout << ob[i].get_i() << "\n";
 }

getch();
return 0;
}
Custom Search