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.
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.