-2

I am basically passing two parameters in the private class and I am trying to access these two parameters in my main function. Since I made those two parameters private, I am using get and set functions to access these parameters, but I am not able to return two values from the get function. Please help me. The last post that asked kind of same question, but this time it has been asked for object oriented concept.

class FirstClass{
  public:
    void setName(int x,int y){
        a = x;
        b = y;
}
    int getName(){
    return a,b;

     }
  private:
    int a,b;
};
demongolem
  • 9,474
  • 36
  • 90
  • 105
  • you need to use two functions to get two return values in this case. – Ravi Dhoriya ツ Jun 05 '14 at 13:49
  • 1
    Or return a struct containing both values. Or pass in variables by reference and copying into those variables. – Tripp Kinetics Jun 05 '14 at 13:50
  • 1
    Note: `a,b` is the comma operator, which doesn't act anything like in Python. – chris Jun 05 '14 at 13:51
  • @chris: ... and please don't overload the comma-operator to do something similar as in Python :D – tgmath Jun 05 '14 at 14:07
  • @tgmath, Too late: `someContainer = 1,3,5,4,7;` Anyway for something like this, it's already in the language somewhat: `auto foo() {return std::make_tuple(1, 3, "abc");}` At least that will be standard in a few months. – chris Jun 05 '14 at 14:14
  • Return a tuple and use http://en.cppreference.com/w/cpp/utility/tuple/tie to store the result – André Jun 05 '14 at 20:34

3 Answers3

2

Either use references:

int getName(int &a1, int &b1) {
    a1 = a;
    b1 = b;
}

or use two functions:

int getA() {
    return a;
}

int getB() {
    return b;
}
wolfPack88
  • 4,163
  • 4
  • 32
  • 47
0

accessors/mutators or getters/setters are intended to get/set only one value. Your code should be like this:

class FirstClass{
  public:
  FirstClass(int x,int y){ //constructor, initialize the values
    a = x;
    b = y;
}
  int getA(){
  return a;
 }

  int getB(){
  return b;
 }

  int setA(const int newVal){ //using const is a good practice
   a=newVal;
 }

  int setB(const int newVal){ //using const is a good practice
   b= newVal;
 }

 // you can use reference/pointer to *obtain* multiple values, although it is rarely used and seems inappropriate in your code
 void getBoth(int& aRef, int& bRef){
   aRef = a;
   bRef = b;
}


  private:
  int a,b;
};
Rakib
  • 7,435
  • 7
  • 29
  • 45
0

You can return a single value or take parameters as value-result arguments ( pointers or references) or return structure with parameters packed. Most probably you will need to access just a or just b separately after all, so why not to just create two accessors

int getNameA(){
  return a;
}

int getNameB(){
  return b;
}
4pie0
  • 29,204
  • 9
  • 82
  • 118