How to access class elements using a non-member function?

I want to access class elements using a function that is not a member of class.
I've written the the following code. I want to compare earth's and mars's circumference using a non member function compare.

How to do it?

Can it be done using friend function?

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <bits/stdc++.h>

using namespace std;

class planet
{
protected:
    double distance;
    int revolve;
public:
    planet(double d, int r)
    {
        distance=d;
        revolve=r;
    }
};

class earth:public planet
{
    double circumference;
public:
    earth(double d, int r):planet(d,r)
    {
        circumference=2*r*3.1416;
    }

    void show()
    {
        cout<<circumference<<endl;
    }
};

class mars:public planet
{
    double c;
public:
    mars(double d, int r):planet(d,r)
    {
        c=2*r*3.1416;
    }

    void show()
    {
        cout<<c<<endl;
    }

};

void compare() //How do I access circumference and c using this function?
{
    if(circumference>c)
        cout<<"Earth"<<endl;
    else if(c>circumference)
        cout<<"Mars"<<endl;
}

int main()
{
    earth e(93000000,365);
    mars m(95000000,400);

    e.show();
    m.show();

    compare();

    return 0;
}
Last edited on
change signature of compare to be something like:
1
2
3
4
bool compare(const planet& planet1, const planet& planet2)
{
...
}


and write accessor methods in your planet class to return whatever member variables you need.

edit: or return a string specifying the planet.
Last edited on
Topic archived. No new replies allowed.