Initialize member variable : member variable « Class « C++ Tutorial






#include <iostream>
using std::cout;
using std::endl;

class MyClass 
{
public:
   MyClass( int c = 0, int i = 1 );

   void add() 
   { 
      count += increment; 
   }

   void print() const; 
private:
   int count;
   const int increment; 
};

MyClass::MyClass( int c, int i ): count( c ),increment( i )
{ 
}

void MyClass::print() const
{
   cout << "count = " << count << ", increment = " << increment << endl;
}

int main()
{
   MyClass value( 10, 5 );

   value.print();

   for ( int j = 1; j <= 3; j++ ) 
   {
      value.add();
      value.print();
   }

   return 0;
}
count = 10, increment = 5
count = 15, increment = 5
count = 20, increment = 5
count = 25, increment = 5








9.5.member variable
9.5.1.Create a getter for member variable
9.5.2.Initialize member variable in constructor
9.5.3.Share static variable among different class instances
9.5.4.Output variable initialization message
9.5.5.Assign value to member variable directly from assignment
9.5.6.increment counter variable with ++ operator
9.5.7.Initialize member variable