Dragonfly Q&A

The proper way to use getters and setters?

0 like 0 dislike

Hey, so I have been stuck on problems I've had with the getters and setters in the object class. I think this is probably a problem with how I am passing arguments, but I am not sure. I have written them how I am used to writing them in Java. Every time I get a position and set its x and y values, they remain 0. I won't post the code for the getters and setters here because I know I shouldn't post much code. What I will post is from my test file:


df::Object *p_obj = new df::Object();


I have also tried...


df::Object p_obj = df::Object();


getPosition returns the pos variable from the Position object as specified in Chapter 4 of the book.

Please let me know if you need any extra information. This has set me back further than is comfortable at this point, and I can't find a satisfactory answer online.


Dragonfly version Windows
asked Sep 12, 2015 in Engine Development by RichardHayes
edited Sep 13, 2015 by RichardHayes

1 Answer

0 like 0 dislike
Best answer

Let me respond by way of explanation.  When you do the following code:

df::Object *p_obj = new df::Object();

The getPosition() call returns a Position object, and you then set the x value with setX().  This works (assuming you've written setX() properly), but does nothing to the position of the original Object. It only changed the X value of the copied (returned) Position from getPosition().

What you want is something like (shown broken into steps for clarity):

df::Position p = p_obj -> getPosition();
p_obj -> setPosition(p);

This way, you change the x-value to 5 in the copied Position object, then set the position of the Object. Make sense?

As a side note not really related to the getter/setter issue, but still a problem to watch out for ... the code:

df::Object p_obj = df::Object();
will cause problems since created object, p_obj, is not allocated out of the heap (i.e., it was not created via "new") and is instead on the stack.  Thus, the object will "go away" after the function/method ends, but the game engine will still refer to it (assuming it was added to the WorldManager in the constructor).  In short, all game objects in Dragonfly must be created via "new".


answered Sep 13, 2015 by claypool
selected Sep 13, 2015 by RichardHayes
Thank you. I am still getting used to pointers and when something is passed by value or by reference.

This was before I coded the WorldManager. All my objects are now created via "new".
More information about Dragonfly can be found on the Dragonfly Home Page.