• Advertisement
Sign in to follow this  

[VC++ 2008] Weird errors with this pointer

This topic is 3458 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

class OtherClass;

class MyClass
{
private:
 OtherClass *mObj;
public:
 MyClass(OtherClass *pObj) : mObj(pObj)
 {
 }
};

class OtherClass
{
public:
 MyClass *create()
 {
  return new MyClass(this);
 }
};

This kind of thing used to work back on older compilers, but in VC++ 2008 I get errors saying this can't be converted to the right type. Do I need to do some ugly casting? Is there a special rule about the type of a this pointer? edit: fixed a typo. [Edited by - d000hg on August 3, 2008 10:08:50 AM]

Share this post


Link to post
Share on other sites
Advertisement
"MyClass(this)" should be OK, I think. The this pointer is always of type "Type* const", but the compiler should cast the const implicitly away (as the pointer is passed by value).

As alvaro said, the type of "new MyClass(this)" is MyClass*, not MyClass. Are you sure the compiler isn't complaining about that?

Share this post


Link to post
Share on other sites
Quote:
Original post by Porthos
The this pointer is always of type "Type* const"

Well, it's const only in const methods.

Share this post


Link to post
Share on other sites
Quote:
Original post by Porthos
"MyClass(this)" should be OK, I think. The this pointer is always of type "Type* const", but the compiler should cast the const implicitly away (as the pointer is passed by value).

As alvaro said, the type of "new MyClass(this)" is MyClass*, not MyClass. Are you sure the compiler isn't complaining about that?
Just a typo, I fixed it. This isn't the real example, since I can't publicly post that.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement