Steve Jobs
Steve Jobs

Reputation: 181

What is the object-oriented idea I'm trying to get at with my scenario?

I have a scenario where I've made a class, call it myClass, and I've realized I need another class, call it myOtherClass, which will be used inside of myClass but not outside of it. I haven't taken a Computer Science class for years, so I can't remember the terminology for what I'm trying to get at. There is no inheritance going on; just that myClass uses myOtherClass, in fact builds a tree of myOtherClass objects, and I want to encapsulate everything properly.

What is the concept I need to be following and what is it in C++ specifically? Please let me know if I need to try and make this question more clear.

Upvotes: 2

Views: 54

Answers (3)

Serge
Serge

Reputation: 674

MyClass is composed of a tree of MyOtherClass objects. The design pattern is one of composition. If you implemented a templated Tree class, your code might look like this:

#include "MyOtherClass.h"

class MyClass
{
public:
 MyClass();
 ~MyClass();
private:
 Tree<MyOtherClass> m_tree;
};

Upvotes: 0

Blob
Blob

Reputation: 569

Sounds like composition. The class owns a private member:

class Edible {};

class Food
{
private:
    Edible eds;
};

Note that this is in some ways similar to private inheritance (although as you mention you're building a tree of them, composition is what you want).

Upvotes: 2

R Sahu
R Sahu

Reputation: 206567

It's called a nested class.

class myClass
{
   class myOtherClass {...}; // myOtherClass is a nested class inside
                             // myClass.

   myOtherClass a;           // a is member variable of myClass.
                             // Its type is myOtherClass.
};

Upvotes: 6

Related Questions