-4
    #include<iostream> 
    using namespace std; 
      
    class Test { 
        int value; 
    public: 
        Test(int v = 0) {value = v;} 
          
        // We get compiler error if we add a line like "value = 100;" 
        // in this function. 
        int getValue() const {return value;}   
    }; 
      
    int main() { 
        Test t(20); 
        cout<<t.getValue(); 
        return 0; 
    } 

Can anybody explain a typical practical scenario where Const function is necessary?

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • There is a metric ton of information on what `const` does when applied to the context of a method on the google. – Andy Sep 06 '20 at 03:58

1 Answers1

-1

The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided.

A const member function can be called by any type of object. Non-const functions can be called by non-const objects only.

https://www.tutorialspoint.com/const-member-functions-in-cplusplus

drum
  • 5,416
  • 7
  • 57
  • 91