"This" pointer

Hi, again

I try to add two complex numbers using "this" pointer.
In "Complex Suma(Complex z)" function the first number is represented by the curent object and the second is represented by the parameter.
The problem is when i compile this code the sum is first number.


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
47
48
49
50
51
52
53
54
#include <iostream>

using namespace std;

class Complex
{
    public:
        int a;
        int b;
        Complex();
        Complex(int x, int y, const char *str);
        Complex Suma(Complex z);
        ~Complex();
};

Complex::Complex()
{
    a = 0;
    b = 0;
}

Complex::Complex(int x, int y, const char *str)
{
    cout << "\n Give the " << str <<endl;
    cout << "\n\t Give the real part : ";
    cin >> x;
    a = x;
    cout << "\n\t Give the imaginary part : ";
    cin >> y;
    b = y;
}

Complex::~Complex()
{

}

Complex Complex::Suma(Complex z)
{
    Complex man;
    man.a = this->a + z.a;
    man.b = this->b + z.b;
    return man;
}

int main()
{
    int x, y;
    Complex R(), R1(x, y, "first number"), R2(x, y, "second number");
    Complex Add, Sum;
    Sum = Add.Suma(R1);
    cout << "\n The sum is : " << Sum.a << " + " << Sum.b << "*i" <<endl;
    return 0;
}
Your Suma function is fine.

The problem is you are adding the 'Add' object, which is 0,0 because it was default constructed.

1
2
3
4
// irrelevent parts removed:
    Complex R1(x, y, "first number");  // <- R1 is whatever user inputs, let's say R1=5,2
    Complex Add;  // Add is default constructed, so Add=0,0
    Complex Sum = Add.Suma(R1);  // <- Sum=Add+R1.   0,0 + 5,2 = 5,2 


If you want to add the two parts the user inputs, then you want to add R1 and R2:

 
Sum = R1.Suma(R2);



Also, if your Complex ctor is getting input from the console [super](which it really shouldn't, but whatever)[/super], then there is absolutely no reason for x and y to be parameters... or even for them to exist at all. They are completely worthless.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Complex::Complex(const char *str) // <- x and y are worthless params, get rid of them
{
    cout << "\n Give the " << str <<endl;
    cout << "\n\t Give the real part : ";
//    cin >> x;  // <- get rid of it
    cin >> a;  // read directly to 'a' instead
    cout << "\n\t Give the imaginary part : ";
//    cin >> y;  // <- ditto
    cin >> b; // <- ditto
}

int main()
{
//    int x, y;  <- no longer need these.  They are worthless.
    Complex R1("first number"), R2("second number");
    Complex Sum = R1.Suma(R2);
    cout << "\n The sum is : " << Sum.a << " + " << Sum.b << "*i" <<endl;
    return 0;
}
Last edited on
Topic archived. No new replies allowed.