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

Related Posts:

  • Exception objects in C++ Exception objects The exception object is available only in catch block. You cannot use the exception object outside the catch block. Following steps happen when you throw an exception and catch: try {  MyException … Read More
  • Exception Handling in C++ Exception Handling in C++ -> We often come across some peculiar problems other than logic or syntax error. They are known as exceptions. -> Exceptions are run time anomalies(errors) or unusual conditions that A progr… Read More
  • Rethrowing an Exception in C++ Rethrowing an Exception in C++ -> A handler may decide to rethrow the exception caught without processing it. In such situations, we may simply invoke throw without any arguments as shown below:       thro… Read More
  • Catch All Exceptions in C++ Catch All Exceptions in C++ -> In some situations, we may not be able to anticipate types of exceptions and therefore may not be able to design independent catch handlers to catch them. In such circumstances, we can forc… Read More
  • Exception specification in C++ Exception specification -> Older code may contain dynamic exception specifications. They are now deprecated in C++, but still supported. A dynamic exception specification follows the declaration of a function, appending … Read More

Translate

Popular Posts