tags:

views:

210

answers:

4

I have a class which looks approximately like this:

class MeshClass
{
public:
    Anchor getAnchorPoint(x, y)
    {
      return Anchor( this, x, y );
    }
private:
    points[x*y];
}

I want to make another class which represents an "Anchor" point which can get access to the Mesh and modify the point, like this:

class Anchor
{
public:
    Anchor(&MeshClass, x, y)
    moveAnchor(x, y);
}

The problem is when I try to make the Anchor in the MeshClass::getAnchorPoint method, something like return Anchor(this, x, y) but because this is const I can't. As a workaround until I get this figured out I have Anchor accepting a reference to the point and moveAnchor moves the point directly.

Edit: The problem was most likely something dumb I was doing with trying to use a Reference. I changed to using a pointer like I normally would and I can pass in this with no complaints from the compiler. I'm almost certain I was getting an error related to this being const, but I can't recreate it so I must just be out of my mind.

+1  A: 

Why do you think this is const? this is a pointer, not a reference. Shouldn't it be return Anchor( *this, x, y);?

Fred Larson
Technically, this actually _is_ const, *this is not.
Joel
Technically, `this` is not const-qualified. It's not modifiable because it's an rvalue, not because it's const. This means that `this` has type `Class *`, but *not* `Class *const`.
Johannes Schaub - litb
A: 

Could you change Anchor to accept a const MeshClass& as parameter, or cast this as (MeshClass) when creating the Anchor ? I am not sure if one can use const_cast<MeshClass>(this) to remove the constness of this.

Timores
+6  A: 

In C++, this is a pointer, not a reference. You could do something like this:

class Anchor; //forward declaration

class MeshClass
{
public:
    Anchor getAnchorPoint(int x, int y)
    {
        return Anchor(*this, x, y );
    }
private:
    int points[WIDTH*HEIGHT];
}

class Anchor
{
public:
    Anchor(MeshClass &mc, int x, int y);
}
Joey Adams
This was probably my problem. I decided to have Anchor accept a pointer rather than a reference, in which case `this` now seems to work fine as a parameter.
Winder
+2  A: 

The constness of this is not a problem. The pointer itself is const, not the value it points to.

Your real problem is here:

class MeshClass
{
public:
    Anchor getAnchorPoint(x, y)
    { 
       return Anchor( *this, x, y );
    }
 private:
     points[x*y];
}
EFraim