objects and methods

A couple of nice people tried to help me understand better how objects and methods work. I know now that the method directly affects the whole object.
But what I don't know still is how it affects it in a general sense.
Could you please help me with this?
Is it that the value that is returned in a method is stored in every variable in the object?
I wouldn't think so.
It doesn't seem to make sense because the object would have different variables. Correct?
I'm still not quite over the hump yet here.
But I really really appreciate you reading this.
And an answer would be even better, but have a nice day anyways.
Seriously. :) Michael.
The return value is just like the return value of anything other function you make, it can be void (nothing), other return some other value that can have whatever meaning you want.
You can think of an object as the variables that go together to make the thing you want. For example, a complex number may be implemented by two doubles called i and r.

Methods are functions that the object provide. So our complex number may have a set method where you can set the real and imaginary values. Or it may have a get method that returns the real value.

The values of the object are available to methods, but unavailable to code that is not a methods of the object.

To illustrate the point, here's a comlpex class.
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
#include <iostream>

class Complex
{
    double    r, i;	// real and imaginary implementation

public:
    Complex(double r_val = 0.0, double i_val = 0.0)
        :    r(r_val), i(i_val)
    {
    }

    void set(double r_val, double i_val)
    {
        r = r_val; i = i_val;
    }

    void get(double &r_val, double &i_val) const
    {
        r_val = r; i_val = i;
    }

    double get_real() const { return r; }
    double get_imaginary() const { return i; }
};

Complex operator+(const Complex &a, const Complex &b)
{
    return Complex(
            a.get_real() + b.get_real(),
            a.get_imaginary() + b.get_imaginary());
}

std::ostream& operator<<(std::ostream& os, const Complex &value)
{
    os << '<' << value.get_real() << ','
       << value.get_imaginary() << '>';
    return os;
}

int main()
{
    Complex a(3.0), b(2.3, -1.0);

    Complex c = a + b;
    std::cout << "c = " << c << std::endl;

    return 0;
}


Complex is a class with private members r and i.

Complex has methods set, get, get_real, get_imaginary and a constructor. These methods can access the private members r and i, but the other functions such as main cannot.

I've defined two operators that use Complex, one for addition and the other for serialisation to an ostream, for convenience later on.

main uses three instances of Complex and the operators.

I hope this helps.
Topic archived. No new replies allowed.