Can an object pass itself to a function (not part of a class i.e. global scope), which modifies that object.
Jun 3, 2021 at 8:26pm UTC
I'm confused as to how to achieve that, most of the examples i have seen have methods present in another class which we instantiate in our object class and use "this" pointer for example anotherclass.foo(this);. Any example would be appreciated.
So currently, the example i am using is this:
1 2 3 4 5 6 7
class Eater{
public :
bool isEating=false ;
void goingtoEat(Eater man){ eating(this ); }
}
void eating(Eater& man2){
man2.isEating=true ;}
But its throwing errors :(
Last edited on Jun 3, 2021 at 8:51pm UTC
Jun 3, 2021 at 9:05pm UTC
this is a pointer.
You can
deference the pointer to get a reference.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// forward declaration
class Eater;
void eating(Eater& man2);
class Eater{
public :
bool isEating = false ;
void goingtoEat(Eater man){
eating(*this );
}
};
void eating(Eater& man2){
man2.isEating = true ;
}
int main()
{
Eater eater;
Eater other;
eater.goingtoEat(other);
}
Side note: I realize your example might just be contrived for demonstration, but the 'Eater man' parameter is never used.
History note: Stroustrup introduced the 'this' pointer before references were introduced.
Last edited on Jun 3, 2021 at 9:08pm UTC
Jun 3, 2021 at 9:23pm UTC
Oh then what would be the addition/deletion in the above code if'Eater man' is never used. And yes it just a special example and is an unpreferable way of writing a code.
Jun 3, 2021 at 9:41pm UTC
I have figured it out, for anyone else the final code would be
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// forward declaration
class Eater;
void eating(Eater& man2);
class Eater{
public :
bool isEating = false ;
void goingtoEat(){
eating(*this );
}
};
void eating(Eater& man2){
man2.isEating = true ;
}
int main()
{
Eater eater;
eater.goingtoEat();
}
Topic archived. No new replies allowed.