Thread: Looping pointer function question

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    24

    Looping pointer function question

    The Entity class looks like this:
    Code:
    class Entity {
    public:
    bool hidestate;
    Entity* parent;
    };
    Code:
    bool Entity::IsHidden()
    {
    	if (hidestate==true) return true;
    	Entity* e = parent;
    	while (e!=NULL)
    	{
    		if (e->hidestate==true) return true;
    		e = e->parent;
    	}
    	return false;
    }
    I'm getting a crash on this line:
    Code:
    if (e->hidestate==true) return true;
    Am I doing something obviously wrong? Thanks.

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You might want to initialize parent to NULL in an Entity constructor -- if you don't, it might well be a random, non-NULL value, which you will then try to dereference in IsHidden(). This constructor might look like e.g.
    Code:
    Entity::Entity() : parent(NULL) {
    
    }
    By the way, if I could suggest a simpler implementation of IsHidden():
    Code:
    bool Entity::IsHidden() {
        if(hidestate) return true;
        if(parent && parent->IsHidden()) return true;
        return false;
    }
    Or something along those lines.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    24
    Thanks. I am learning a lot really fast!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  4. Function pointer question
    By sbayeta in forum C Programming
    Replies: 9
    Last Post: 08-06-2004, 08:15 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM