Let see an example code to understand these questions, when you will call the increment in display function you will get the error because you are breaking the rule.
#include<iostream>
using namespace std;
class Demo
{
int m_value;
public:
Demo()
{
m_value = 0;
}
int incrementValue();
//const member function
void display() const;
};
int Demo::incrementValue()
{
return (++m_value);
}
void Demo::display() const
{
int value = incrementValue();
cout<< value <<endl;
}
int main()
{
class Demo obj;
obj.display();
return 0;
}
Output:
Compilation error
So to avoid this you need to do some tricks, Now see the code.
#include<iostream>
using namespace std;
class Demo
{
int m_value;
public:
Demo()
{
m_value = 0;
}
int incrementValue();
void display() const;
};
int Demo::incrementValue()
{
return (++m_value);
}
void Demo::display() const
{
int value = (const_cast<Demo*>(this))->incrementValue();
cout<< value <<endl;
}
int main()
{
class Demo obj;
obj.display();
return 0;
}
Code will compile successfully.
Remark: Never try to break your promise might get undefined behavior.
Answer:
Let see an example code to understand these questions, when you will call the increment in display function you will get the error because you are breaking the rule.
Output:
Compilation error
So to avoid this you need to do some tricks, Now see the code.
Code will compile successfully.
Remark: Never try to break your promise might get undefined behavior.
need an explanation for this answer? contact us directly to get an explanation for this answer