Disambiguating between const and non-const member

  • Thread starter Martin Magnusson
  • Start date
M

Martin Magnusson

Suppose I have a class like this one:

class A
{
int* getint()
{
return const_cast<int*>(getint());
}

const int* getint() const
{
//some complicated code
return i;
}

int* i;
};

That is, I have a const member returning a const pointer, but I also
want to be able to access a non-const pointer to the same data, without
doing a lot of copy-paste coding. So I'd like to call the const function
from the non-const function. For cleanliness, I'd like the functions to
have the same name, and disambiguate between the two based on the
context where they are called. This is generally not a problem, but with
this implementation, the process gets stuck in an infinite recursive
loop when the non-const method is called.

Is there a way to call the const getint() from within the non-const
getint(), or would I have to copy the body of the const method, or
rename it const_getint, to get rid of the recursive behaviour?
 
R

Robert Bauck Hamar

Martin said:
Suppose I have a class like this one:

class A
{
int* getint()
{
return const_cast<int*>(getint());
}

const int* getint() const
{
//some complicated code
return i;
}

int* i;
};

That is, I have a const member returning a const pointer, but I also
want to be able to access a non-const pointer to the same data, without
doing a lot of copy-paste coding. So I'd like to call the const function
from the non-const function. For cleanliness, I'd like the functions to
have the same name, and disambiguate between the two based on the
context where they are called. This is generally not a problem, but with
this implementation, the process gets stuck in an infinite recursive
loop when the non-const method is called.
Yes.

Is there a way to call the const getint() from within the non-const
getint(), or would I have to copy the body of the const method, or
rename it const_getint, to get rid of the recursive behaviour?

Convert this to a const A*, and call getint() for that pointer:
const A* p = this;
return const_cast<int*>(p->getint());
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top