0

I'll get straight to the point. To be honest, I think there is an answer to this, but I don't know how to word it.

int playerXCoord = Player.getPosition().x
//this is just an example

How do you define something in C++?

I am familiar with classes and instances but I would like to know how to do this (in C/C++).

Andreas Grapentin
  • 5,499
  • 4
  • 39
  • 57
Ricky
  • 122
  • 1
  • 1
  • 9

2 Answers2

3

Something like this perhaps:

class Player
{
public:
    struct Coordinates
    {
        int x;
        int y;
    };

    Coordinates const& getPosition() const
    {
        return position_;
    }

private:
    Coordinates position_;
};

Now you can do e.g.

Player player;
int x = player.getPosition().x;

Note that you don't have to return a reference, the getPosition function could just as easily have been defined as

Coordinates getPosition() const { ... }

The "trick" is to have a function which returns the correct structure. That structure can of course be a complete class with its own member functions, which means you can easily "chain" many member function calls as long as you return an object of some kind.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

If you want to do something like that, try to use setters and getters methods, e.g. :

class Player
{
private:
    int m_X;
    int m_Y;

public:
    int getX() const;
    int getY() const;
    void setX(int x);
    void setY(int y);
}

Getters methods should be like:

int Player::getX()
{
   return m_X;
}

And setters like:

void Player::setX(int x)
{
   m_X = x;
}

Then you can do something them in this way:

Player player;
player.setX(5);
player.setY(10);
int playerXcoord = player.getX();
...

You can also handle both coords in one method:

void Player::setCoords(int x, int y)
{
   m_X = x;
   m_Y = y;
}

The advantage of this approach is that all of your class components can't be accessed directly outside the class. It prevents from accidental modifications.

Matt Black
  • 31
  • 1
  • 4