Q:

How to call a non-const member function from a const member function in C++?

0

How to call a non-const member function from a const member function in C++?

All Answers

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

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.

#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.

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
When should I use references, and when should I us... >>
<< Can I delete pointers allocated with malloc() ijn ...