overloading pointers

it shows zero value for d3 but it's suppose to add d1 and d2 value to get total in d3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
    #include<stdexcept>
#include<conio.h>
#include <iostream>
#include<string.h>
using namespace std;
class Distance
{
private:
double feet ;
double inches;
public:
	Distance():feet(0),inches(0) {}
	Distance(double ft, double inch) : feet (ft ) , inches (inch){}
	void Display()
	{
		cout<<feet<<"-"<<inches<<endl;
	}
	void getDistance()
	{
		cout<<"feet:";
		cin>>feet;
		cout<<endl;
		cout<<"inches:";
		cin>>inches;
	}
	Distance Distance::operator += (Distance d1)
	{
		Distance d2;
		d2.feet =d1.feet+feet;
		d2.inches=d1.inches/12+inches;
		return 
			d2;
		
	}
};
int main () 
{
Distance d1(3,5),d2,d3;
d1.Display();
d2.Display();
d2.getDistance();
d2+=d1;
d3+=d2;
d3.Display();
}
Your operator += doesn't modify anything from this, so it does not even change the state of your objects.
Thank you why doesn't the operator modify what is the problem in my code
Because you create a local variable d2 and modify it, rather than modifying this.

This is what you have (wrong):
26
27
28
29
30
31
32
33
34
	Distance Distance::operator += (Distance d1)
	{
		Distance d2;
		d2.feet =d1.feet+feet;
		d2.inches=d1.inches/12+inches;
		return 
			d2;
		
	}
Try this instead:
26
27
28
29
30
31
32
	Distance &Distance::operator += (Distance const &other)
	{
		feet += other.feet; //calculation is still wrong
		inches += other.inches/12; //calculation is still wrong
		return *this;
		
	}
Note that your math is still wrong and will not give the correct results, but at least the code is correct.
Thank you can you tell me what *this is or refer me an article on it or can't you return a object for it , that would make it less complicated
closed account (o3hC5Di1)
Hi there,

Within an object of a class this is a pointer to that same objects location in memory.
So by doing return *this; you are effectively returning the object in its current state.

Similarly, you could use this within your class to access members:

std::cout << this->feet;

Which can be useful sometimes when dealing with templates.

All the best,
NwN
Thank you
Topic archived. No new replies allowed.