Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

You may do it like this:

void changeval(istream& in) { in >> k; }
...
changeval(cin);

Is that what you need?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top