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.
The ability to define inputs as member functions allows you to use cin. get and cin. getline to treat user input as parts of a function. This is a simple and straightforward way to get input from a user and then manipulate it through programming.
Arguments are passed by value; that is, when a function is called, the parameter receives a copy of the argument's value, not its address. This rule applies to all scalar values, structures, and unions passed as arguments. Modifying a parameter does not modify the corresponding argument passed by the function call.
The "c" in C++ cin refers to "character" and "in" means "input". Thus, cin means "character input".
The cin object in C++ is an object of class iostream. It is used to accept the input from the standard input device i.e. keyboard. It is associated with the standard C input stream stdin. The extraction operator(>>) is used along with the object cin for reading inputs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With