When is 'this' const?

S

Simon Elliott

In a class function body, I'm trying to pass 'this' to another function.
I'm getting an error because 'this' seems to have become const. Any
ideas as to why this has happened?

extern void DoSomethingWithFoo(foo* fooPtr);

virtual void foo::doStuff(void)
{
DoSomethingWithFoo(this); // error: can't convert foo* const to foo*
}

Very weirdly, in another very similar class, exactly the same idiom has
worked. The only difference is that the function is inlined into the
header in the case which doesn't work. Is there some rule that says that
'this' is const when inlined into the header?
 
R

Ron Natalie

Simon Elliott said:
In a class function body, I'm trying to pass 'this' to another function.
I'm getting an error because 'this' seems to have become const. Any
ideas as to why this has happened?

extern void DoSomethingWithFoo(foo* fooPtr);

virtual void foo::doStuff(void)
{
DoSomethingWithFoo(this); // error: can't convert foo* const to foo*
}
By any chance is "doStuff()" really defined:

virtual void foo::doStuff() const { ...

Inside a const method, the this pointer is of type "const foo*."
 
S

Simon Elliott

Simon Elliott said:
In a class function body, I'm trying to pass 'this' to another function.
I'm getting an error because 'this' seems to have become const. Any
ideas as to why this has happened?

extern void DoSomethingWithFoo(foo* fooPtr);

virtual void foo::doStuff(void)
{
DoSomethingWithFoo(this); // error: can't convert foo* const to foo*
}

Very weirdly, in another very similar class, exactly the same idiom has
worked. The only difference is that the function is inlined into the
header in the case which doesn't work. Is there some rule that says that
'this' is const when inlined into the header?

I've now discovered that this issue was due to a silly mistake I made
further down the inheritance chain. I may have misunderstood the error
message as it said "foo* const" which I read as "const foo*"...
 
M

Micah Cowan

Ron Natalie said:
By any chance is "doStuff()" really defined:

virtual void foo::doStuff() const { ...

Inside a const method, the this pointer is of type "const foo*."

But the error message indicates that this is of type "foo *
const". Weird.
 

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

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,372
Latest member
LucretiaFo

Latest Threads

Top