Q:

What is the “mutable” keyword in C++?

0

What is the “mutable” keyword in C++?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

This keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function.

Let see the below code, where I am incrementing the mutable variable in a const member function. If you will remove the mutable keyword you will get a compiler error.

#include <iostream>
using namespace std;
class Demo
{
public:
    Demo():m_accessCount(0)
    {
    }
    int GetData() const
    {
        return (++m_accessCount);
    }
private:
    mutable int m_accessCount;
};
int main()
{
    Demo obj;
    cout << obj.GetData()<<endl;
    return 0;
}

Output: 1

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Interview Questions For Experienced

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to handle the exception in C++?... >>
<< Why virtual functions cannot be static in C++?...