I have a class that contains objects of two other classes. I need one of the classes to be able to get data from the other one. Here's an example.
class Nom{ /*says what we're eating*/ };
class Chew{ /*stuff that needs to know about what we are eating from nom*/ };
class BigBurrito
{
Nom n;
Chew c;
};
How about passing a pointer to the instance of Nom
into Chew
? Along these lines:
class Nom {};
class Chew
{
private:
Nom *m_nom;
public:
Chew(Nom *nom)
: m_nom(nom)
{}
};
class BigBurrito
{
private:
Nom m_nom;
Chew m_chew;
public:
BigBurrito()
: m_chew(&m_nom)
{}
};
You can either make a pointer to the other class a member of the class
class Nom{
Chew* chew;
};
class Chew{ /*stuff that needs to know about what we are eating from nom*/ };
class BigBurrito
{
Nom n; //contains pointer to c
Chew c;
};
or pass it via a parameter to the function that performs the operation.
class Nom
{
void performOperationOnChew(Chew& c);
};
class Chew{ /*stuff that needs to know about what we are eating from nom*/ };
class BigBurrito
{
Nom n;
Chew c;
void doTheOperation()
{
n.performOperationOnChew(c);
}
};
The second option is cleaner OOP, since Chew
doesn't logically belong to Nom
.
Chew
is an action, as I guess in retrospect its name suggests (I find it interesting that my reflex reaction to this without thinking about design issues is pass in a pointer...hmm), then why is it contained in BigBurrito
like that? Seems a bit odd - Stuart Golodetz 2012-04-03 20:39
Just pass in a reference to n
(Nom
) to your Chew
constructor.