Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ using 'this' as a parameter

Tags:

c++

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.

like image 955
Winder Avatar asked Feb 25 '10 22:02

Winder


People also ask

Can I pass a function as a parameter in C?

In C programming you can only pass variables as parameter to function. You cannot pass function to another function as parameter. But, you can pass function reference to another function using function pointers.

Can you pass by reference in C?

Pass by reference Even though C always uses 'pass by value', it is possible simulate passing by reference by using dereferenced pointers as arguments in the function definition, and passing in the 'address of' operator & on the variables when calling the function.

Can you use a variable as a parameter?

Variables that are taken in by a method are called parameters. They are declared in the opening parentheses of a method and are assigned a value whenever the method is called. If the method is called again, they are assigned new values.

What are parms in C?

Parameters in C functionsA Parameter is the symbolic name for "data" that goes into a function. There are two ways to pass parameters in C: Pass by Value, Pass by Reference.


2 Answers

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);
}
like image 174
Joey Adams Avatar answered Sep 22 '22 00:09

Joey Adams


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];
}
like image 28
EFraim Avatar answered Sep 20 '22 00:09

EFraim