Object-Oriented Programming In C++: Constant Objects

Contents:

1. Constant Variables.

2. Constant Member Functions.

Constant Variables:

Making variables constant ensures their values are not accidentally changed. Just like the built-in data types (int, double, char, etc…), class objects can be made const by using the const keyword. All const variables must be initialized at time of creation. For example, we define a constant object from Time class and initialize its members: const Time noon( 12, 0, 0 ); Once a constant class object has been initialized via constructor, any attempt to modify the member variables of the object is disallowed, as it would violate the constness of the object. This includes both changing member variables directly (if they are public), or calling member functions that sets the value of member variables. For Example:
  1. class IntData
  2. {
  3. public:
  4. int value;
  5. IntData()
  6. {
  7. value= 0;
  8. }
  9. void SetValue(int v)
  10. {
  11. value = v;
  12. }
  13. int GetValue()
  14. {
  15. return value ;
  16. }
  17. };
  18. int main()
  19. {
  20. const IntData cIntData; // calls default constructor
  21. cIntData.value = 5; // violates const
  22. cIntData.SetValue(5); // violates const
  23.  
  24. return 0;
  25. }

Constant Member Functions:

From the above example, consider the following call: cout << cIntData.GetValue(); This will cause a compile error. This is because constant class objects can only call constant member functions, then now a constant member function is a member function that guarantees it will not change any class variables or call any non-constant member functions. To define a constant member function, we have to add const keyword in its prototype and definition:
Prototype: ReturnType FunctionName(param1,param2…) const; Definition: ReturnType FunctionName(param1,param2…) const { …}
So we can redefine GetValue() to be a constant member function, then we can call it for a constant objects:
  1. int GetValue()
  2. {
  3. return value ;
  4. }
Note: constructors and destructors can not be constants. Full Example:
  1. // Declaration of the class Time.
  2. class Time {
  3. public:
  4. // Constructor function to initialize private data.
  5. // Default values are 0 (see class definition)
  6. Time( int hr, int min, int sec ) // default constructor
  7. {
  8. setTime( hr, min, sec );
  9. }
  10.  
  11. // set functions
  12.  
  13. // Set the values of hour, minute, and second.
  14. void setTime( int h, int m, int s ) // set time
  15. {
  16. setHour( h );
  17. setMinute( m );
  18. setSecond( s );
  19. }
  20.  
  21. // Set the hour value
  22. void setHour( int h ) // set hour
  23. {
  24. hour = ( h >= 0 && h < 24 ) ? h : 0;
  25. }
  26.  
  27. // Set the minute value
  28. void setMinute( int m ) // set minute
  29. {
  30. minute = ( m >= 0 && m < 60 ) ? m : 0;
  31. }
  32.  
  33. // Set the second value
  34. void setSecond( int s ) // set second
  35. {
  36. second = ( s >= 0 && s < 60 ) ? s : 0;
  37. }
  38.  
  39. // get functions (normally declared const)
  40.  
  41. // Get the hour value
  42. int getHour() const // return hour
  43. {
  44. return hour;
  45. }
  46.  
  47. // Get the minute value
  48. int getMinute() const // return minute
  49. {
  50. return minute;
  51. }
  52.  
  53. // Get the second value
  54. int getSecond() const // return second
  55. {
  56. return second;
  57. }
  58.  
  59. // print functions (normally declared const)
  60.  
  61. // Display military format time: HH:MM
  62. void printMilitary() const // print military time
  63. {
  64. cout << ( hour < 10 ? "0" : "" ) << hour << ":"
  65. << ( minute < 10 ? "0" : "" ) << minute;
  66. }
  67.  
  68. // Display standard format time: HH:MM:SS AM (or PM)
  69. void printStandard() // should be const
  70. {
  71. cout << ( ( hour == 12 ) ? 12 : hour % 12 ) << ":"
  72. << ( minute < 10 ? "0" : "" ) << minute << ":"
  73. << ( second < 10 ? "0" : "" ) << second
  74. << ( hour < 12 ? " AM" : " PM" );
  75. }
  76.  
  77. private:
  78. int hour; // 0 - 23
  79. int minute; // 0 - 59
  80. int second; // 0 - 59
  81. };
  82.  
  83. int main()
  84. {
  85. Time wakeUp( 6, 45, 0 ); // non-constant object
  86. const Time noon( 12, 0, 0 ); // constant object
  87.  
  88. // MEMBER FUNCTION OBJECT
  89. wakeUp.setHour( 18 ); // non-const non-const
  90.  
  91. noon.setHour( 12 ); // non-const const
  92.  
  93. wakeUp.getHour(); // const non-const
  94.  
  95. noon.getMinute(); // const const
  96. noon.printMilitary(); // const const
  97. noon.printStandard(); // non-const const
  98. return 0;
  99. }
The Output:
Compiling... Fig07_01.cpp d:fig07_01.cpp(14) : error C2662: 'setHour': cannot convert 'this' pointer from 'const class Time' to 'class Time &' Conversion loses qualifiers d:\fig07_01.cpp(20) : error C2662: 'printStandard' : cannot convert 'this' pointer from 'const class Time' to 'class Time &' Conversion loses qualifiers Time5.cpp Error executing cl.exe. test.exe -2error(s), 0 warning(s)
Note: You can find the full source code of this example in code.zip file.

Tags

Add new comment