Jay
Jay

Reputation: 79

Act upon an object calling a function?

So say I was using this to create an object:

MyClass myObject;

and I had the function inside of the class to act upon the object. So one way could be using parameters, like this:

MyClass foo(MyClass a) {
return a;
}

Seems simple. But is there a way so I can use myObject.foo() and it would still return a even though I'm not using it as a parameter? One example could be some of the methods in std::string - you can use std::string.swap(), using the object for the swap() function.

Is there a way, or am I being stupid?

Upvotes: 0

Views: 83

Answers (3)

Mooing Duck
Mooing Duck

Reputation: 66951

Inside every member function is a magic secret parameter, which is a pointer to the object who's method was called, and the parameter's name is this.

MyClass& foo() { //returns reference to existing MyClass instead of making copies
    this->print(); //call a different member
    return *this;  //return a reference to itself. Common for `operator=` and such.
}

Upvotes: 1

Jherico
Jherico

Reputation: 29240

First off, keep in mind that you original code of

MyClass foo(MyClass a) {
  return a;
}

does not actually return a. It returns a copy of a, which itself is a copy of whatever instance of MyClass you passed into foo. If you want to pass in a given object, act on it and return it, you need to use references, like so

MyClass & foo(MyClass & a) {
  return a;
}

This will ensure that the a you get back from a call to foo is the exact same object you passed into it.

Additionally, an object can always return a reference to itself in one of its members...

class MyClass { 
  MyClass & foo() { return *this; }
}

This is especially useful in classes where you might want to chain a large number of operations together...

MyClass my = MyClass().foo().bar("Hello").baz(5);

Upvotes: 2

aschepler
aschepler

Reputation: 72431

Inside a class's (non-static) member function, you can use *this to name the object the function was called on.

So:

MyClass MyClass::foo() {
    return *this;
}

(Notice that function returns a copy of the object. If you don't want a copy, use a reference as in @Jherico's answer.)

Upvotes: 0

Related Questions