1 // Fig. 10.5: Increment.cpp
2 // Member-function definitions for class Increment demonstrate using a
3 // member initializer to initialize a constant of a built-in data type.
4 #include <iostream>
5 using std::cout;
6 using std::endl;
7
8 #include "Increment.h" // include definition of class Increment
9
10 // constructor
11 Increment::Increment( int c, int i )
12 : count( c ), // initializer for non-const member
13 increment( i ) // required initializer for const member
14 {
15 // empty body
16 } // end constructor Increment
17
18 // print count and increment values
19 void Increment::print() const
20 {
21 cout << "count = " << count << ", increment = " << increment << endl;
22 } // end function print
I can't explain command line 11 > 13 int Increment.cpp
It's a constructor for Increment Class but I haven't seen something like that before.
Please help!
Increment::Increment( int c, int i ){
count = c;
increment =1;
}
If you do it this way, it will still work but not recommended. Before entering the body of the constructor code, all the private,protected or public variables will be assigned a default value. For this relatively simple example, it won't make much difference. But as your code gets more complex, you are better off assigning values to all the class variables even before entering the body of the constructor.
Note that even the order in which you do this matters. For example
Increment::Increment(int c, int i):count(c),increment(i){}
is not the same as
Increment::Increment(int c, int i):increment(i),count(c){}
although in this relatively simple example it will make no difference. If you are on Linux, try compiling with -Wall and you will get a warning stating that increment will be initialized after count.