|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now! |
|
#1
|
|||
|
|||
|
Using an object within itself
Is it possible to use and object within itself?
For example I have a class called state. Can a state object also hold other states? Im sure the n queens problem comes in here somewhere..... |
|
#2
|
|||
|
|||
|
No, I don't think so. You'd create an overflow, as you're likely referring to about the queens. The first class has memory allocated for its members, of which is another instance of the class, which has members, of which is another instance of the class...never ending loop.
You could use work arounds though, where objects are declared on the heap if some condition is met. Each class instance stores pointers to said objects, which would be null if no object was created. The condition could be how deeply nested your classes are, or whatever you need. |
|
#3
|
|||
|
|||
|
I can't speak for C++, but you can definitely do that in Java, so I'll be surprise if that's not possible in C++. One of the elementry data structure is the Link List, you create a Link object, and inside that, it can hold other Link objects.
Actually, in a Link object, it holds references to other Link objects. Code:
class Link {
private Link nextLink;
private Link prevLink;
private Object dataItem;
Link() {
}
...
}
Last edited by Robo : November 7th, 2002 at 06:53 AM. |
|
#4
|
|||
|
|||
|
Yes, it's possible to use objects within other objects of the same class, but they must be aggregated rather than contained. For example:
class State { State *otherState_; }; |
|
#5
|
|||
|
|||
|
Exactly. I suspect that is what happens in Robo's java example as well, but I've never used the language. Robo's example seems like an implementation of a link list, where each link holds pointers to the previous and next link, if any. But no link actually contains other links.
|
|
#6
|
|||
|
|||
|
Yip, in Java, objects are called by references, similar to pointers in C/C++
|
|
#7
|
|||
|
|||
|
you can certainly do this in c++. you just need to use a predeclaration for the class. i can't quite remember but the class should look something like this
class state; //pre declaration must be used, it's like an IOU class state { private: state* pState; public: }; |
|
#8
|
|||
|
|||
|
Heh, everyone's saying the same thing, they just all have different names for it...
|
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > Using an object within itself |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|