Hi all,

I want to know if there is a smart way in c++ to test if my variable (or pointer) was already initialized? For example, I have a linked list, and I want to add an item to that list.
If would like to do some thing

if (!(initialized(*head) ))  { // if head wasn't initialized
   // ...
   // create first item, and save this pointer as head of this list

} else {  head already exists. Create the next link
   // ...
}

Any suggestions how to go about it?

Thanks,
-R

Recommended Answers

All 5 Replies

No. All you have to do is initialize pointers to NULL when declared, e.g. int *ptr = NULL; or set them to NULL in c++ class constructors. There is no such test for other kinds of variables.


But you can either write your own or use an existing smart pointer c++ class. google for "c++ smart pointer" and you will find examples and tutorials.

I'll have the constructor set *head=NULL; seems shortest (the destructor will finish its job with the same *head=NULL). Also this smart pointers seems worth reading so thanks for that too.
-R

*head = NULL in the constructor is probably incorrect. How did you declare variable head? If something like this: char* head; then in the constructor it should be head = NULL; (note that there is no star).

I'm not sure I followed you correctly:
The constructor was used only to initialize *head=NULL, without creating new objects. There is a different function for that. If the constructor was set to create objects then it would have initialized head, and there wouldn't be any need to test it.
The code is something like this:

class point {
public:
	int x, y;
	point *next;
	void setpoint(int X, int Y) { x=X; y=Y; }
};

class polygon {
private:
	point *head;
	point *last;
public:
	polygon() {head=NULL; last=NULL;} // note that last points to the **last defined** link. On the first point last=head
	void addpoint(int X, int Y) {
		if (head == NULL) {	// first point
			head=new point;
			head->setpoint(X,Y); // new points accepted only through point::setpoint(), and not through any constructor
			last=head;
		} else {	// not the first point
			last->next=new point;
			last=last->next;
			last->setpoint(X,Y); // the same
		}
	}
};

>The constructor was used only to initialize *head=NULL,

No it isn't. Read your code again -- its the same as I suggested.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.