Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes - Get function - return more than one value

Let's suppose we have:

Class Foo{
    int x,y;

    int setFoo();
}

int Foo::setFoo(){
    return x,y;
}

All I want to achieve is form my get function to return more than one value. How can I do this?

like image 314
Bogdan Maier Avatar asked Dec 06 '25 08:12

Bogdan Maier


2 Answers

C++ doesn't support multiple return values.

You can return via parameters or create an auxiliary structure:

class Foo{
    int x,y;

    void setFoo(int& retX, int& retY);
};

void Foo::setFoo(int& retX, int& retY){
    retX = x;
    retY = y;
}

or

struct MyPair
{
   int x;
   int y;
};

class Foo{
    int x,y;

    MyPair setFoo();
};

MyPair Foo::setFoo(){
    MyPair ret;
    ret.x = x;
    ret.y = y;
    return ret;
}

Also, shouldn't your method be called getFoo? Just sayin...

EDIT:

What you probably want:

class Foo{
    int x,y;
    int getX() { return x; }
    int getY() { return y; }
};
like image 76
Luchian Grigore Avatar answered Dec 08 '25 21:12

Luchian Grigore


You can have reference parameters.

void Foo::setFoo(int &x, int &y){
    x = 1; y =27 ;
}
like image 23
Daniel A. White Avatar answered Dec 08 '25 21:12

Daniel A. White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!