Rahul Iyer
Rahul Iyer

Reputation: 21025

How to pass self by reference from within the object being passed?

I am confused about the syntax I need to use.

I have:

class Foo {

public:

    void bar(Baz& grr){

    }

}

Another class:

class Baz{

}

And:

class Jay : public Baz{
public:
   void doStuff(){
        Foo thing();
        thing.bar(); //Here is the problem ? How do I pass this instance to this function ?
   }
}

How do I pass an instance of Jay to Foo::bar(Baz& grr), from within doStuff() ? If I try to use this the compiler says to dereference it using *. How do I do that ?

Upvotes: 0

Views: 444

Answers (3)

Hatted Rooster
Hatted Rooster

Reputation: 36503

You dereference by using the * operator like so *this. Dereferencing returns the pointed-to object and since this is a pointer to the current instance *this will return the object of the current instance.

Note, however, if you save this reference and that instance goes out of scope it will be destroyed and you will be left with a dangling reference that will cause undefined behaviour when attempted to be read.

Upvotes: 1

jpo38
jpo38

Reputation: 21544

this is a pointer to the current object. You need to "dereference" it to get the object's reference:

thing.bar(*this);

Upvotes: 1

Freddie Chopin
Freddie Chopin

Reputation: 8860

Try doing exactly as compiler suggests:

thing.bar(*this);

By dereferencing the pointer, you "create" a reference.

Upvotes: 2

Related Questions