Say I have two .cpp files: oranges.cpp and basket.cpp. They have the classes orange and basket, respectively. My main program generates many baskets which in turn generate many oranges. So basically, main will have many objects of Baskets; and baskets will have many objects of Oranges. If I have a function in orange that needs to know the color of my basket, how would I go about finding the color of the basket?
orangle.cpp
class oranges
{
void whichColorBasket()
{
// get the color of the basket the orange is in...?
}
}
basket.cpp
class basket
{
int color;
void basket()
{
for(int i = 0; i < 10; i++)
oranges *o = new oranges;
}
}
I know my syntax may not be perfect but how would I access the datamember of basket from a function in orange (orange is an object created by basket).
Sending the color a parameter isn’t an option as there are too many oranges and the color of the basket may change during runtime.
I read somewhere that static functions would do the trick, but they only work if they are in the same .cpp file.
So, what do I do?
Static functions are almost certainly not the answer here.
You would probably need to pass a reference to the “parent”
Basketto theOrangesobject, which it can then interrogate to find the colour.For example:
Whether you use a pointer or a reference will depend on whether the
Orangescan ever move betweenBaskets.