Null object in C++

Started by
3 comments, last by ext 18 years, 10 months ago
I have a 5 by 5 square field in which each square can have an occupant. This is a small battle field and so there may only be 3 characters on the field at once and I was wondering what is the best way to represent a square's occupant if the square is empty? I tried using NULL but that seems to not work the way it does in java.
Advertisement
I'm sure there are differences but it is not that different, in my opinion. What did you try exactly. The following would work okay:
class CSquare{protected:  COccupant* m_pOccupant;public:  CSquare( void )  {    m_pOccupant = NULL;  }  COccupant* const GetOccupant( void )  {    return m_pOccupant;  }};CSquare* pSomeSquare = ...;if ( pSomeSquare->GetOccupant() == NULL )  // No occupant in this square.


Maybe if you detail your question with an example or actual code, the precise difference or misuse/misinterpretation may emerge.

Greetz,

Illco
ok I found my problem I had COccupant m_pOccupant instead of COccupant* m_pOccupant.

Is there another option then making all my objects pointers?
Ok. The problem is that an instance of an object always has valid contents. Although they may not be what you want, there is no generic way of determining whether the object is occupied or not -- it always is. In Java all objects behave as if they are pointers to objects, although you never get to see a pointer.
You could make a 3*3 matrix of Objects, call them for example Field, now you're
deriving von the Field class every different type of a field, player1, player2, player3, empty,... and let the compiler worry about the right thing, by using virtual functions.

This topic is closed to new replies.

Advertisement