C++ Pointers

Started by
11 comments, last by Andorien 16 years, 4 months ago
Some questions to ask yourself:
1. Why do you need pointers here? Why does memory need to be on the heap?
2. Could I use references instead?
3. How about just having it on the stack?
4. Why do I need a create function? Using new is idiomatic and expected in C++, do I have a need for something else?
5. Does the drawing of a position belong in the Position class? Does this tie the position class to the renderer that you're using?
6. Why is there no name for the variable that's being declared on your second line?!?! (Joking! I know that it's just a careless mistake.)
Advertisement
Quote:Original post by Steve Elliott
Ok, I've got what I wanted now for the Position Class - any errors here?


csPosition* Position = NULL;Position = Position->create();Position->reset();Position->draw();csPosition* csPosition::create(){    csPosition* Position = new csPosition;    return Position;}

That's what you get for trying to apply something you don't need yet ;).
Ezbez already pointed out that your intention in this example is unclear, as to why you need to have that object on free-store. Without seeing the context we can not certainly tell you if your example is good.

Another point would be your naming convention. You are generally free to choose your own naming scheme, though there are some generally accepted conventions on certain things: class names should start with a capital letter, in C++ there is no need to have any class prefix (like c or in your case cs).

A better way to put your example would be (assuming it really should be on the free-store rather than heap space):

Position* somePosition = new Position();
...

There is no need for a "create" method since this is what the constructor of the class is responsible for.
Besides that, by calling your create() method from a null-pointer you've set yourself in the world of unknown behaviour by the C++ standard. It may (it will most probably, since your method does not access any member variables) work, but it doesn't have to, so never do that again.
My Blog
If you're dead set on having a create function in your class (which, as someone pointed out, isn't necessary), a better way to do it would be to use a static method.

You would do it like this:
csPosition* Position = NULL;Position = csPosition::create(); // Notice we access the static method through the class, not a pointer or an instance;Position->reset();Position->draw();static csPosition* csPosition::create() // Static methods are associated with a class rather than an instance.  Their only limitation is that they can't access non-static methods or variables.{    csPosition* Position = new csPosition;    return Position;}

This topic is closed to new replies.

Advertisement