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.
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.
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.
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.
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.
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);
}
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With