Search code examples
c++encapsulation

How to access private variables using functions only


#include <iostream>

using namespace std;

int main()
{
    asksUser();
    printLarger(int, int);
    return 0;
}

int asksUser()
{
    int num1, num2;
    cout << "Enter number ";
    cin >> num1;
    cout << "Enter number ";
    cin >> num2;
    return num1;
    return num2;
}

int printLarger(int num1, int num2)
{
 //Will compare the two ints and print out biggest

}

So I had a simple problem which I could've quite easily just done in main but I thought, why not try and do how I've been taught in Clean Code and split everything into tiny functions. Granted both my functions still do two things which isn't what they preferred... Turns out it wasn't as simple as I thought.


Solution

  • You cannot return twice, but you don't have to: one purpose behind writing a function in the first place is reusing its logic.

    You can write a function askUser that returns an int, and call it twice from the main, like this:

    int a = askUser();
    int b = askUser();
    printLarger(a, b);