Home > front end >  Result of method used to call another method yields inconsistent results. C
Result of method used to call another method yields inconsistent results. C

Time:10-13

I currently have to write a program that allows a user to pick between two objects to test. This isn't the same program exactly but it's the same premise.

class defined by header file

#include <iostream>

class example {
private:
    int x;
public:
    example() {
        x = 10;
    }
    void setNum(int input) {
        x = input;
    }
    int getNum() {
        return x;
    }
};

Test main and selectObj method

#include <iostream>
#include "Header.h"



example selectObj(example A, example B) {
    int selection;
    std::cout << "Select object 1 or 2: ";
    while (true) {
        std::cin >> selection;
        if (selection == 1)
            return A;
        else if (selection == 2)
            return B;
        else
            std::cout << "Inavlid option, try again: ";
    }
}



int main() {
    example test1, test2;
    selectObj(test1, test2).setNum(25);
    std::cout << selectObj(test1, test2).getNum();

    return 0;
}

selectObj is supposed to return an object. It runs but it isn't doing what setNum is supposed to do.

Suppose you choose option 1 for both calls of selectObj. It looks something like this.

Select object 1 or 2: 1
Select object 1 or 2: 1
10

It should have printed out 25 but instead, setNum isn't really changing the value of test1.

However, if I write

test1.setNum(25);
std::cout << test1.getNum();

Then it does indeed set test1's x value to 25.

Again, this isn't exactly like the program I had written (it is changed now and wouldn't like to rewrite that). However, it is an identical representation of the same concept.

CodePudding user response:

The problem is that you're passing and returning the arguments by value instead of reference. To solve this you can pass and return the arguments by reference as shown in the below modified code:

main.cpp

#include <iostream>
#include "Header.h"


//return and pass by reference
example& selectObj(example &A, example &B) {
    int selection;
    std::cout << "Select object 1 or 2: ";
    while (true) {
        std::cin >> selection;
        if (selection == 1)
            return A;
        else if (selection == 2)
            return B;
        else
            std::cout << "Inavlid option, try again: ";
    }
}



int main() {
    example test1, test2;
    selectObj(test1, test2).setNum(25);//this sets the value of x member of the object that the user chooses
    
    std::cout << selectObj(test1, test2).getNum();

    return 0;
}

The output of the above program when the user enters option 2 is:

Select object 1 or 2: 1
Select object 1 or 2: 1
25

  •  Tags:  
  • c
  • Related