A class that contains an instance of itself

Started by
13 comments, last by popsoftheyear 11 years, 5 months ago

Did you try to compile this? Simple question like this could just be tested. Learn to be more independent.

There is no harm in asking the question. Just because something can be compiled and appear to work doesn't mean it is correct.
Advertisement

[quote name='D.Chhetri' timestamp='1351395282' post='4994627']
Did you try to compile this? Simple question like this could just be tested. Learn to be more independent.

There is no harm in asking the question. Just because something can be compiled and appear to work doesn't mean it is correct.
[/quote]
This is one of the reason I asked the question. In C++, there are many dangerous things that the compiler allows but never gives a warning about.
An invisible text.
You probably want something like:

[source]
class Menu
{
public:
Menu() : subMenu(0) { }
~Menu(){ delete subMenu; }

void
setSubMenu(Menu *m){ subMenu = m; }

private:
Menu *subMenu;
};

void f()
{
Menu *mainMenu = new Menu();
mainMenu->setSubMenu(new Menu());
}
[/source]

In other words, set the submenu pointer to 0 in the constructor and assign it elsewhere.
In theory, you could actually recursively include objects using some funky C++ template programming.


template <int level>
struct Menu
{
Menu<level + 1> subMenu;
...
};

template<>
struct Menu<3> // hierarchy ends here
{
...
};

static void foo()
{
Menu<0> menu;
menu.subMenu.subMenu.subMenu; // ok
menu.subMenu.subMenu.subMenu.subMenu; // error, no such member
}


Not that this is the way to do it, but it illustrates that C++ is flexible enough to do this kind of perverted solution.

openwar - the real-time tactical war-game platform

An alternative type of having an instance in itself (I realize this isn't exactly what you're trying to do)

class Profiler {
public:
Profiler();
~Profiler() { }
// This gives us a global version without limiting us to only 1. We can make other Profiler
// objects if we want.
static Profiler &GetGlobalInstance() {
static Profiler prof;
return prof;
}
[...] stuff
};

Then, you know, modify it accordingly if you need an instance per thread, or if you need to ensure synchronization is handled, or whatever.

This topic is closed to new replies.

Advertisement