Declaration: < type flag > function name (parameter table) const;
Explain:
(1) const is a part of function type, and this keyword is also required in the implementation part.
(2) The const keyword can be used to distinguish overloaded functions.
(3) The constant member function cannot update the member variables of the class, nor can it call the member functions in the class that are not decorated with const. It can only call the constant member functions.
A. const is a part of function type through examples, and this keyword is also required in the implementation part.
#include <iostream.h> class A{ private: int w,h; public: int getValue() const; int getValue(); A(int x,int y) { w=x,h=y; } A(){} }; int A::getValue() const //This keyword is also included in the implementation part { return w*h; //???? } void main() { A const a(3,4); A c(2,6); cout<<a.getValue()<<c.getValue()<<"cctwlTest"; system("pause"); }
B. Understand the overload of const keyword through examples
class A{ private: int w,h; public: int getValue() const { return w*h; } int getValue(){ return w+h; } A(int x,int y) { w=x,h=y; } A(){} }; void main() { A const a(3,4); A c(2,6); cout<<a.getValue()<<c.getValue()<<"cctwlTest"; //Output 12 and 8 system("pause"); }
C. Understand through examples that constant member functions cannot update any data members
class A{ private: int w,h; public: int getValue() const; int getValue(); A(int x,int y) { w=x,h=y; } A(){} }; int A::getValue() const { w=10,h=10;//Error because the constant member function cannot update any data members return w*h; } int A::getValue() { w=10,h=10;//Data members can be updated return w+h; } void main() { A const a(3,4); A c(2,6); cout<<a.getValue()<<endl<<c.getValue()<<"cctwlTest"; system("pause"); }
D. Understand by example
1. Constant member functions can be called by other member functions.
2. But other non member functions cannot be called.
3. You can call other regular member functions.
class A{ private: int w,h; public: int getValue() const { return w*h + getValue2();//Wrong cannot call other non member functions. } int getValue2() { return w+h+getValue();//Regular member function can be called correctly } A(int x,int y) { w=x,h=y; } A(){} }; void main() { A const a(3,4); A c(2,6); cout<<a.getValue()<<endl<<c.getValue2()<<"cctwlTest"; system("pause"); }