*this

i don't understand

Page 1 of 1

6 Replies - 444 Views - Last Post: 09 September 2009 - 11:21 AM Rate Topic: -----

#1 learnplaycreate  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 119
  • Joined: 27-August 09

*this

Post icon  Posted 08 September 2009 - 06:14 AM

i should acknowledge that pointers have been the conceptual struggle in learning c++, pointer arithmetic for moving the pointer around two dimensional arrays was the first hurdle, my current understanding is that using the unary ++ postfix on the pointer moves the pointer to point at the next vertical element or if 2d arrays are arrays of arrays the ++ operator moves the pointer to the next array the the array of arrays. would love to know if that conception is wrong although it is not the subject of this question, this question relates to the pointer *this. from the advice i've received form tutorials and other posts it is better form/more correct/ safer/ more elegant, to use *this while overloading functions. i'm really very unsure how to use it to improve the code. below are two examples of code that both compile although return different results, the first is without the use of *this and the second with; in the lines 33 - 38 while overloading the operator +;

the first example as can be see from the line 37 cout, and the line 50 call to function print() set the value of val3 three members as intended, the second example although line 37 outputs the intended value of the val3 members, the line 50 call to function print() clearly shows that the assignment was not successful as intended and val3 members have been given the value of the val1 members without taking into consideration the addition operator. it is clear to me that i am using the *this incorrectly, despite the success in compiling the code.

if you have some spare time, i could really do with an explanation of how i should have used *this to achieve the same result i get from the first version. my thought at the moment is that maybe i should change the void operator =() function to int operator =() and return *this, as without the change in type i get an error while compiling the code to the effect that i can't return a value in a void function.

thank you very much for taking the time to read the long winded question and even more if you ahve taken some time to help
Liam

example 1
#include<iostream>
#include<string>
using namespace std;

class twoplace{
	private:
		float x;
		float y;
		float z;

	 public:
	twoplace(float a=0,float b=0){
		x=a;
		y=b;
	}
	void print(){
		cout <<endl<<"["<<x<<","<<y<<"]"<<endl;

	}
	void setvalue(float a, float b){
		x = a;
		y = b;
	}
	void addition(twoplace val1,twoplace val2){
		x = val1.x+val2.x;
		y = val1.y+val2.y;
		cout <<endl<<"["<<x<<","<<y<<"]"<<endl;
	}
	void operator =(twoplace val3){			 //this overloads the '=' operator
		x = val3.x;
		y = val3.y;
	}
	twoplace& operator +(twoplace val3){			 //this overloads the '+' operator
		twoplace val4;
		val4.x = x+val3.x;
		val4.y = y+val3.y;
		cout <<endl<<"["<<val4.x<<","<<val4.y<<"]"<<endl;
		return val4;								//this returns the value of the addition to val3.
	}
};

int main()
{
	twoplace val1(4);		   //check the constructor for the defult value for the y cordinate
	twoplace val2;
	twoplace val3;
	val2.setvalue(6,5);
	val3 = val1 + val2;							 //the two overload functions in the class allow for this statment

	val3.print();
	return 0;
}



example 2
#include<iostream>
#include<string>
using namespace std;

class twoplace{
	private:
		float x;
		float y;
		float z;

	 public:
	twoplace(float a=0,float b=0){
		x=a;
		y=b;
	}
	void print(){
		cout <<endl<<"["<<x<<","<<y<<"]"<<endl;

	}
	void setvalue(float a, float b){
		x = a;
		y = b;
	}
	void addition(twoplace val1,twoplace val2){
		x = val1.x+val2.x;
		y = val1.y+val2.y;
		cout <<endl<<"["<<x<<","<<y<<"]"<<endl;
	}
	void operator =(twoplace val3){			 //this overloads the '=' operator
		x = val3.x;
		y = val3.y;
	}
	twoplace& operator +(twoplace val3){			 //this overloads the '+' operator
		twoplace val4;
		val4.x = x+val3.x;
		val4.y = y+val3.y;
		cout <<endl<<"["<<val4.x<<","<<val4.y<<"]"<<endl;
		return *this;								//this returns the value of the addition to val3.
	}
};

int main()
{
	twoplace val1(4);		   //check the constructor for the defult value for the y cordinate
	twoplace val2;
	twoplace val3;
	val2.setvalue(6,5);
	val3 = val1 + val2;							 //the two overload functions in the class allow for this statment

	val3.print();
	return 0;
}



Is This A Good Question/Topic? 0
  • +

Replies To: *this

#2 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3089
  • View blog
  • Posts: 19,137
  • Joined: 14-September 07

Re: *this

Posted 08 September 2009 - 08:51 AM

The reason the answer is wrong in the second example is because you are returning a reference to the val1 object. The first example is correct in that it performs the addition correctly. Example two does the addition, but then only returns the object on the left of the addition operator (val1 in this case).

The best way to explain is to lay out what exactly happens:

//in example 1
val3 = val1  + val2;
//the compiler sees two objects being added. It goes to see if the 
//+ operator is overloaded
//it is so it executes that function
//in the first example, you create a temp object and do the addition
//you then return this temp object
//the compiler then sees if you have overloaded the '=' operator
//you have so the compiler executes that function
//val3 is assigned the values of val4 (a reference to the temp object in '+)



Now the same series of events applies for example two except that you have decided to return *this. this is a keyword denoting the current object, in this case the object that is the "left" o the addition sign, the calling object. You do the addition with the temp variable, but then completely disregard it and return *this which is the value of val1, which is then assigned to val3 as in the above steps.


Hopefully that helps. Let me know if I can clarify something.
Was This Post Helpful? 0
  • +
  • -

#3 learnplaycreate  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 119
  • Joined: 27-August 09

Re: *this

Posted 09 September 2009 - 07:09 AM

thanx mate i have a better understanding now. so apparently for efficiency it would be better not to create the temp object at all, how is it possible to do the equation and have it return the correct value for val3, should l replace all the val4's with *this? intuitively that seems like the wrong move (logic is often counter intuitive at first glance, explanation and retraining of thought processes can usually overcome this). thanx again
Was This Post Helpful? 0
  • +
  • -

#4 trixt.er  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 46
  • View blog
  • Posts: 419
  • Joined: 28-September 08

Re: *this

Posted 09 September 2009 - 07:28 AM

One of the more common practices of the this pointer is in setting private member variables in a class.
Here is the code in C++ and Java. Notice C++ uses the arrow operator. If you declare an object with
the new operator you should use the -> operator to access variables in C++. Similar to this.

// First in C++

MyClass::MyClass(String status)
{
   this->status = status;
}

// And in Java...

public MyClass(String status)
{
   this.status = status;
}


I really found a lot of uses for *this and the arrow op.
Was This Post Helpful? 0
  • +
  • -

#5 viveks89  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 29
  • Joined: 06-January 09

Re: *this

Posted 09 September 2009 - 07:36 AM

 
 twoplace& operator +(twoplace val3){			 //this overloads the '+' operator
		twoplace val4;
		val4.x = x+val3.x;
		val4.y = y+val3.y;
		cout <<endl<<"["<<val4.x<<","<<val4.y<<"]"<<endl;
		return *this;								//this doesnt return the value of the addition to val3... It returns the value of the object which called this operator
	}



Here the problem is that a temporary object val4 is created... but u didnt return the val4 after adding
But returned the value of the initial object itself... If u really wana use this in this code do it this way
val4.x = this -> x + val3.x;
val4.y = this -> y + val3.y;
cout << endl << "[" << val4.x << "," << val4.y << "]" << endl;
return val4;


Was This Post Helpful? 0
  • +
  • -

#6 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 5954
  • View blog
  • Posts: 23,217
  • Joined: 23-August 08

Re: *this

Posted 09 September 2009 - 08:36 AM

Let's look at some of your code.

First the assignment operator:
void operator =(twoplace val3){             //this overloads the '=' operator
        x = val3.x;
        y = val3.y;
    }


The assignment operator needs to return a reference to the object, not void, so that the return value can be placed in the variable on the left-hand side of the statement.

It should also accept as an argument a const-reference to the object to be assigned, which assures that the object is not copied (for performance reasons) and the compiler will prevent it from being changed, as it should not be.

Also, a common thing to do when creating copy constructors and overloaded operators is to name the incoming variable rhs, for "right-hand side," because that incoming variable represents the right hand side of an assignment:
twoplace &operator =(const twoplace &rhs)
{       
    // Note this code is assigning the values in the passed object
    // to the member variables in THIS object. There is an implicit this
    // pointer here.
    x = rhs.x;
    y = rhs.y;

    // If we wanted to make the this pointer explicit, we could do
    // this->x = rhs.x;
    // this->y = rhs.y;
    //
    // The same thing is happening in both cases.

    // Now we need to return a reference to our newly-modified object, i.e., [b]this[/b] object, which
    // is what we changed. We dereference the this pointer and return that.
    return *this; 
}


Now, apply that knowledge I just gave you to your overload of the addition operator.
Was This Post Helpful? 0
  • +
  • -

#7 learnplaycreate  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 119
  • Joined: 27-August 09

Re: *this

Posted 09 September 2009 - 11:21 AM

thank you all very much i really appreciate it. this site has enhanced and accelerated my learning experience more then i could have imagined thee weeks ago when i joined, hopefully one day i'll be able to return the favor to others trying to learn.
Lpc
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1