Advertisement
193030

02. const and functions

Jul 8th, 2021
880
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Dog
  6. {
  7.     int age;
  8.     string name;
  9. public:
  10.     Dog() { age = 3; name = "dummy"; }
  11.  
  12.     // const parameters
  13.     void setAge(const int& a) { age = a; cout << "Set age const" << endl; } // when the parater is const
  14.     void setAge(int &a) { age = a; cout << "Set age non-const" << endl; /// when the parameters non-const
  15.      }
  16.  
  17.     // const return value
  18.     const string& getName() { return name; }
  19.  
  20.     // const function
  21.     void printDogName() const // works when the object is non const
  22.     {
  23.         cout << name << " const " << endl;
  24.     //  age++; this doesn't work cause of const
  25.     }
  26.  
  27.     void printDogName() // works when the object is non const
  28.     {
  29.         cout << name << " non-const " << endl;
  30.         //  age++; this doesn't work cause of const
  31.     }
  32. };
  33.  
  34.  
  35. int main()
  36. {
  37.     Dog d;
  38.     const int age = 10;
  39.     int age2 = 20;
  40.     d.setAge(age);
  41.     d.setAge(age2);
  42.     d.printDogName();
  43.  
  44.    
  45.     const Dog d2;
  46.     d2.printDogName();
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement