Using a static data member in a class : static « Class « C++






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

1.Static member variables and functions
2.static functions and ID numbers for objects
3.Static member data.
4.Accessing static members without an object.
5.Accessing static members using non-static member functions.
6.Static member functions.
7.static members in classes
8.Calculate salary using static members.
9.static counter
10.Update static field in member method
11.Reference static method along with class name
12.static field is shared among instances