1

I have the below function

class p{
public :
string const& PrintData() const
{
    cout << "const" << str;
    const_cast<ConstFunctions *>(this);
    PrintData();
    return str;
}
string const& PrintData()
{
    cout << "non-const" << endl;
    return str;
}
private :
string str="Hello";
}

int main()
{
const p p1;
p1.PrintData();
}

I am expecting the below ::

constHello non-constHello

Because i have removed the constantness of the object

But i am getting in to infinite recursive loop

3 Answers3

4

The statement const_cast<ConstFunctions *>(this); doesn't do anything useful. It does a const_cast and simply throws away the result. The compiler will most likely optimize it away.

Then you do the recursive call, which will just call itself, not the non-const function.

You probably meant to do

const_cast<p*>(this)->PrintData();
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3

This line...

string const& PrintData() const
{
    cout << "const" << str;
    const_cast<ConstFunctions *>(this);   //It doesn't work this way, you didn't use the result
    PrintData();     //THis causes a recursive loop
    return str;
}

You have a recursive problem there, You didn't catch the return value of the const_cast hence the result was discarded, and the compiler will optimize that line away.

See, whenever you call a member function like PrintData() in your code, its called like this

this->PrintData();
//actually, like 
p::PrintData( /*cv*/ this); //The cv qualification of 'this' depends on the cv of the object, in your case, const

The this pointer always carries the cv qualification of the calling object. See What does "cv-unqualified" mean in C++?

What you want to do is to cast away the cv qualifications of this and use the resulting this to call the non-const version

string const& PrintData() const
{
    cout << "const" << str;
    return const_cast<p*>(this)->PrintData();
}
Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
2

p1 is const, so it calls:

string const& PrintData() const

In this function you call PrintData, but because you are in a const function the compiler will look to call your const version, which will cause the recursive loop.

The line:

const_cast<ConstFunctions *>(this);

Doesn't actually do anything since your class doesn't have this type in its type hierarchy and you're also not doing anything with in.

If you really want to call the non-const version then do:

const_cast<p*>(this)->PrintData();

But you should really ask yourself why you are trying to do this...

Sean
  • 60,939
  • 11
  • 97
  • 136