C++ examples for Class:Member Function
Initializing a const Data Member with a Member Initializer
#include <iostream> using namespace std; class Counter /* w w w . java 2s .co m*/ { public: Counter( int c = 0, int i = 1 ); // default constructor // function addCounter definition void addCounter() { count += increment; } // end function addCounter void print() const; // prints count and increment private: int count; const int increment; // const data member }; // end class Counter // constructor Counter::Counter( int c, int i ) : count( c ), increment( i ) // required initializer for const member { } // print count and increment values void Counter::print() const { cout << "count = " << count << ", increment = " << increment << endl; } #include <iostream> using namespace std; int main() { Counter value( 10, 5 ); cout << "Before incrementing: "; value.print(); for ( int j = 1; j <= 3; ++j ) { value.addCounter(); cout << "After increment " << j << ": "; value.print(); } }