How to access members from a function declared outside the Class

I want to access members of classes, from functions that are declared outside the class.

For example I have a class PC, and that class has an object member that is another class caled CPU. The clases are not inside each other, they are declared outside each other.

The function is outside both of these clases. Now I need to access both members from PC and CPU.

Here is the code example:

1
2
3
4
5
6
7
8
9
10
11
12
class PC{
int price;
CPU c;
};

class CPU{
int speed;
};

void print(pc &p)
{
}


I want to print all the information for a pc, it's price, it's cpu speed etc..
How can I access members from outside both classes.
No, they have to be private, that's the way they ask them to be in the faculty problems. So we learn how to access private data members in these cases.
You should provide methods in your classes to access their private data members.
I'd then go with public (read-only?) methods.

Or if the exercise is to learn about friendship, declare the print() function as a friend of the other classes.
I get methods should do, but how will I read the speed of the CPU through the PC class?

@webJose, I heard that too, can u please show me an example of how that is done? for example, access the CPU speed through the PC class.
Friendship is explained here: http://www.cplusplus.com/doc/tutorial/inheritance/ .

If the print() function is made friend of PC and CPU, it will be able to read all private members of PC and CPU.
Ok, then how about the get method? Is there a way to access CPU through PC class, using methods ?! (Without declaring it as friend) ?

I just wanna learn both ways, to be more sure.
Thank You.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class PC
{
    CPU _cpu;

public:
    const CPU& CPU() const { return _cpu; }
};


void print(const PC &pc)
{
    const CPU &cpu = pc.CPU();
    //Access public members of the CPU class here through the cpu variable.
    ...
}


Note that I used the const keyword. This is to avoid modification of the member variable of type CPU. This could be a major headache for you if you haven't studied const correctness. Remove the const keyword if it is too much for you right now.
Last edited on
Topic archived. No new replies allowed.