operator= Not As Expected?

Hi there! I'm trying to make it so that when a pointer is created for my class and its set to NULL, that it's automatically changed to create a new MyClass();

1
2
3
4
5
6
7
GameObject* GameObject::operator= (const GameObject* &rhs)
{
	if (rhs == NULL)
		return new GameObject();

	return (GameObject*)rhs;
}


This simply isn't getting called when I have a GameObject *ptr and I set it to NULL like so:

GameObject *ptr = NULL;


So what's going on here, is there any appropriate way to do this? I know thee's probably somebody ripping out their eyeballs like "WHY WOULD YOU WANT TO MAKE A NEW ONE EVERY TIME?" But, just bare with me here. I'm trying to avoid having to do null pointer checks all over the place, unless there's a better way to do that? But anyway, my question is how to do what I'm trying to do, override it when it's being set to null.
Last edited on
Why don't you just create an ordinary GameObject object?

 
GameObject obj;

Now it can't be null.
The operator=(...) isn't called with a pointer just the object itself. The operator simply isn't meant for that purpose.
On top of what coder777 said, also, if even if you were using objects,

GameObject obj = someValue;

wouldn't call the assignment operator, but a constructor. Initialization is not the same as assignment.

To do what you want, I guess you'd need to implement your own smart pointer class, and override the assignment operator of that class to do the dynamic construction of the object.
Last edited on
In response to Peter87, I'm actually creating a GameObject inside of a class called Transform and creating a Transform inside of the class GameObject, hence I need to use a pointer somewhere.

And I had read about it using a constructor operator. But I see. A smart pointer class eh... Will have to look into that.
I had read about it using a constructor operator.

The idea is that if you override operators on a class, those operators will work on objects of that class. But a pointer is not an object; it's a fundamental type that is basically just an integer that stores a memory address. If you perform operations on a pointer (e.g. assignment) then the operation will be the one appropriate to a pointer type, not the one for the object.

This is true for a constructor as well.

A smart pointer class eh... Will have to look into that.

A smart pointer is basically a class that mimics the semantics and behaviour of a pointer, but with additional behaviour built in.

See, for example, std::shared_ptr in C++11, or boost::shared_ptr if you're using C++03. Shared pointers don't give you the specific behaviour you're looking for, but they're an easy-to-understand example of a smart pointer that might help illustrate the concept.
Last edited on
Topic archived. No new replies allowed.