Passing input as a function argument using cin

Nikhil Gupta picture Nikhil Gupta · Jan 4, 2014 · Viewed 21.6k times · Source

My program:

class test
{
    int k;
    public:
    void changeval(int i){k=i;}
};
int main()
{   
    test obj; 
    int i;
    cin>>i;
    obj.changeval(i);
    return 0;
}

Is there any way, by which i can directly pass input from the user as an argument to the function changeval(int), without even initializing value to i??

I mean, i don't want to declare a variable just to pass value to a function. Is there any way i can avoid it? If yes, can I use it for constructors also? Thanks.

Answer

Cornstalks picture Cornstalks · Jan 4, 2014

Nope. Now, you could put this into a function:

int readInt(std::istream& stream)
{
    int i;
    stream >> i; // Cross your fingers this doesn't fail
    return i;
}

// Then in your code:
obj.changeval(readInt(std::cin));

But of course, this still creates an int (it just moves it to the readInt function).

In reality, you have to create some object/memory space for the int to live in, so you can read it and pass it. Where you do this can be changed. But to simply answer your question: no.