Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Is this typically how I would set up C++ set and get member functions ?  (Read 1054 times)

0 Members and 1 Guest are viewing this topic.

S_BISHOP

  • Newbie
  • *
  • Posts: 15
    • View Profile
    • Email
Hello I come from Diploma student Java background.
I would like to know if this is typically how i would set up the get and set member functions in C++

virtual double getX();
virtual void setX(double &newX);

double* Spritable::getX(){return &x;}
void Spritable::setX(double &newX){x = newX;}


and then would I retrieve the values stored at those memory addresses pointed to, by de-referencing
somthing like this ?

p.getTexture().loadFromFile(activeLevelStructuresImages[0], sf::IntRect(*p.getX(), *p.getY(), *p.getWidth(), *p.getHeight()));


Or return references such as this ?

virtual double& getX();
virtual void setX(double &newX);

double& Spritable::getX(){return x;}
void Spritable::setX(double &newX){x = newX;}




if this is so, Yes I think I do understand the textbook logic behind these operations, such as pointers and References after reading "Jumping into C++" a first time. I just would like to be sure if this is how its done. The last thing I wont to do is learn bad habits or incorrect operations.

Thanks Please let me know.
« Last Edit: August 22, 2014, 01:17:58 pm by S_BISHOP »

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32504
    • View Profile
    • SFML's website
    • Email
Re: Is this typically how I would set up C++ set and get member functions ?
« Reply #1 on: August 22, 2014, 01:25:36 pm »
For primitive types, you just pass and return them by value. This is both simpler and more optimized.

double getX() const {return x;}
void setX(double newX) {x = newX;}

But you should consider your class at a higher level, and make it provide services rather than walls of properties that you just get and set.

So you would end up with:

p.loadTexture(activeLevelStructuresImages[0]);

instead of

p.getTexture().loadFromFile(activeLevelStructuresImages[0], sf::IntRect(*p.getX(), *p.getY(), *p.getWidth(), *p.getHeight()));
Laurent Gomila - SFML developer

S_BISHOP

  • Newbie
  • *
  • Posts: 15
    • View Profile
    • Email
Re: Is this typically how I would set up C++ set and get member functions ?
« Reply #2 on: August 22, 2014, 01:54:37 pm »
Thanks Laurent. This was a good reply. I now understand.