Calling const member function from non-const member function.
Most of the time we have to declare two version of same function i.e. one is const and other is non-const according to the needs to used that function on const data and non-const object. For example : lets have a simple example :
#include
#include
using namespace std;
class B {
public:
B(int j) : i(j) {}
void Show(void) const
{
cout<<"Const Version : i == ";
cout<<i;
}
void Show(void)
{
cout<<"Non-Const Version : i == ";
cout<<i;
}
private:
int i;
};
void main()
{
const B b(12);
cout<<"Caling from const object : \n";
b.Show();
B bb(10);
cout<<"\n\nCaling from non-const object : \n";
bb.Show();
_getch();
}
OUTPUT :
Caling from const object :
Const Version : i == 12
Caling from non-const object :
Non-Const Version : i == 10
In such a case we have to duplicate the code in both function. But duplication is always avoidable. So we have to find solution to this problem : There may be different solution exist but the most appropriate is given below : That is calling const function from non-const part :
void Show(void) const
{
cout<<"Const Version : i == ";
cout<<i;
}
void Show(void)
{
cout<<"Non-Const Version : i == ";
// this->Show() // Results into endless loop. Refer Note
(static_cast (this))->Show();
// or (static_cast (*this)).Show();
}
It solve our purpose.
Note : If we directly call const Show function from non-const Show() means without casting it, results into a endless loop. Infact Show function recursively calls it self and formed endless loop. Thats why first cast this pointer to const and then call show function.
Thanx
#include
#include
using namespace std;
class B {
public:
B(int j) : i(j) {}
void Show(void) const
{
cout<<"Const Version : i == ";
cout<<i;
}
void Show(void)
{
cout<<"Non-Const Version : i == ";
cout<<i;
}
private:
int i;
};
void main()
{
const B b(12);
cout<<"Caling from const object : \n";
b.Show();
B bb(10);
cout<<"\n\nCaling from non-const object : \n";
bb.Show();
_getch();
}
OUTPUT :
Caling from const object :
Const Version : i == 12
Caling from non-const object :
Non-Const Version : i == 10
In such a case we have to duplicate the code in both function. But duplication is always avoidable. So we have to find solution to this problem : There may be different solution exist but the most appropriate is given below : That is calling const function from non-const part :
void Show(void) const
{
cout<<"Const Version : i == ";
cout<<i;
}
void Show(void)
{
cout<<"Non-Const Version : i == ";
// this->Show() // Results into endless loop. Refer Note
(static_cast (this))->Show();
// or (static_cast (*this)).Show();
}
It solve our purpose.
Note : If we directly call const Show function from non-const Show() means without casting it, results into a endless loop. Infact Show function recursively calls it self and formed endless loop. Thats why first cast this pointer to const and then call show function.
Thanx
Comments
Post a Comment