Oatskits
Oatskits

Reputation: 25

Two classes in a larger class share data

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;
};

Upvotes: 1

Views: 112

Answers (3)

Luchian Grigore
Luchian Grigore

Reputation: 258668

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.

Upvotes: 1

Stuart Golodetz
Stuart Golodetz

Reputation: 20656

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)
    {}
};

Upvotes: 1

spencercw
spencercw

Reputation: 3358

Just pass in a reference to n (Nom) to your Chew constructor.

Upvotes: 0

Related Questions