(C++) Answer of exercise \#5: The many types of const

February 24, 2017 · View on GitHub

 

 

 

 

 

(C++) Answer of exercise #5: The many types of const

 

This is the answer of exercise #5: The many types of const.

 

The five types of const are:

  1. const variable
  2. const argument
  3. const return type
  4. const member function
  5. const member

 

The five types of const prevent the following from modification:

 

  1. const variable: the variable
  2. const argument: the argument
  3. const return type: this only mostly applied to references to members of a class. Then, const can prevent the original member from being modified.
  4. const member function: all non-mutable class members
  5. const member: the member

 

Below are examples of each type of const.

 

 

 

 

 

Example of a const variable

 

This applies to both local and global variables.

 


int main() {   const int dozen = 12;   //dozen cannot be changed }

 

 

 

 

 

Example of a const argument

 


void Cout(const std::string& anyString) {   //anyString cannot be changed   std::cout << something << std::endl; }

 

 

 

 

 

Example of a const return type

 


struct Values {   const std::vector<int>& GetValues() const   {     //Even after returning a reference to mV, mV cannot be changed     return mV;   }   private:   std::vector<int> mV; };

 

 

 

 

 

Example of a const member function

 

Nearly all 'getters' are const member functions.

 


struct MyClass {   double GetValue() const   {     //Getting mValue does not change the (non-mutable) members of MyClass     return mValue;   }   private:   double mValue; };

 

 

 

 

 

Example of a const member

 


struct Person {   Person(const bool isMale) : mIsMale(isMale) {}   const bool mIsMale; //After construction mIsMale cannot be changed };