23 Nov 2019

  • November 23, 2019
  • Amitraj
Constant Member functions in C++


-> A constant (const) member function can be declared by using const keyword, it is used when we want a function that should not be used to change the value of the data members i.e. any type of modification is not allowed with the constant member function.

-> The const member functions are the functions which are declared as constant in a program. The object called by these functions can not be modified. It is recommanded 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 function can be called by non const objects only.

-> Here is the syntax of const member function in C++ language.

            datatype    function-name   const();



// Cpp program to demonstrate constant member functions.


#include<iostream>

using namespace std;

class   Demo

{

     int val;

     public:

                 Demo(int x=0)

          {

                  val=x;

           }

      int  getvalue()  const

      {

               return  val;

       }

};

int main()

{

      Demo d(28);

       Demo  d1(8);

 cout<<d.getvalue()<<" ";

cout<<d1.getvalue();

return 0;

}


OUTPUT:

28   8

Translate

Popular Posts