Using a static data member in a class
#include <iostream>
using namespace std;
class CBox
{
public:
static int objectCount;
CBox(double lv, double bv = 1.0, double hv = 1.0): m_Length(lv),
m_Breadth(bv),
m_Height(hv)
{
cout << "Constructor called.";
objectCount++;
}
CBox()
{
cout << "Default constructor called.";
m_Length = m_Breadth = m_Height = 1.0;
objectCount++;
}
double Volume() const
{
return m_Length*m_Breadth*m_Height;
}
private:
double m_Length;
double m_Breadth;
double m_Height;
};
int CBox::objectCount = 0;
int main()
{
CBox boxes[5];
CBox cigar(8.0, 5.0, 1.0);
cout << CBox::objectCount;
cout << boxes[2].objectCount;
return 0;
}
Related examples in the same category