Call by reference C++ confusion

In summary, the goal of the program is to overload the extraction operator for cout so that it can handle multiple types of data.
  • #1
shivajikobardan
674
54
Homework Statement
Why do ostream &os? What does it do? Why not just do "ostream os"? What happens in memory when we do this call by reference thing?
Relevant Equations
none
Full code goes here: The goal of the program is to overload the extraction operator for cout.

Code:
#include<iostream>
using namespace std;class Time
{
private:
    int hour;
    int min;
public:
    Time()
    {
        hour=min=0;
    }
    Time(int h,int m)
    {

        hour=h;
        min=m;
    }
    Time operator+(Time t)
    {
        Time t1;
        int m=min+t.min;
        t1.hour=hour+t.hour+m/60;
        t1.min=m%60;
        return t1;

    }
    Time operator+(int x)
    {

        Time t;
        t.hour=hour+x;
        t.min=min;
        return t;
    }
    friend void operator<<(ostream &os,Time t );
};

void operator<<(ostream &os,Time t)
{

    cout<<"Hour : "<<t.hour<<"min:"<<t.min<<endl;
}int main()
{
    Time t1;
    Time t2(8,40);
    Time t3(5,30);
    Time t4(2,30);
    t1=t2+t3+t4;
    cout<<t1;
    return 0;
}
Please guide how to understand this. Tell me any prerequisite that I'm missing, that'd be immensely helpful than giving me hand holded solution.
 
Physics news on Phys.org
  • #2
When I do just "ostream os" instead of "ostream &os", I get the below error;
Screenshot 2023-03-31 150143.png
If anyone could share figures for what's happening in memory, that'll be hugely useful. A picture is worth 1000 words! :)
 
Last edited:
  • #3
The best explanation I can give, which might not be 100% accurate, is that the overloaded << operator expects its first argument to be a reference to the ostream class, not the class itself. This restriction is the same as the ostream class member operator.
 
  • #4
thank you for the reply. I need to learn about call by address and call by reference first.
 
  • #5
shivajikobardan said:
thank you for the reply. I need to learn about call by address and call by reference first.
It's somewhat confusing, IMO. In the time before C++, the two types of calls were call by value and call by reference. These call types refer to what happens with a parameter when a function is called or invoked. In call by value, the function receives the value of the parameter, so if a function modifies that parameter, the change isn't reflected in the caller's variable, In call by reference, the function actually has access to the parameter, so any change that the function makes to the parameter is reflected in the caller's variable. In C, all calls were by value, but call by reference was simulated by making the parameter an address; i.e., a pointer to a variable. Because the pointer was passed by value, no the pointer's value doesn't change, but what's at that address can change.

C++ added a new type of parameter, a reference parameter. It works almost identically to the way that call by pointer address works, except that the semantics are different. IOW, a call by pointer address looks different from a call with a reference parameter.

Here's a short example program that shows all three function call types.
C++:
#include<iostream>
using std::cout; using std::endl;

void CallByValue(int val)
{
	val = 2;
}

void CallByPtr(int* pVal)
{
	*pVal = 2;
}

void CallByRef(int& val)
{
	val = 2;
}int main()
{
	int num = 5;
	// Call by value can't change value of its argument.
	CallByValue(num);
	cout << "num = " << num << endl;

	// Call by pointer address can't change value of its argument,
	//   but can change the value pointed to.
	CallByPtr(&num);
	cout << "num = " << num << endl;

	num = 5;        // Reset num.
	// Call by reference can change the value of its argument.
	CallByRef(num);
	cout << "num = " << num << endl;	
}

Note that only CallByRef() can modify its argument. CallByPtr() doesn't modify its argument, &num, but it modifies what's at that address, namely, num. CallByValue() can't modify its argument at all.

It's interesting to me that the assembly code that MSFT Visual Studio generates for CallByPtr() and CallByRef() are exactly the same, even though the way these functions are called is different. Of course, the code that the compiler generates is implementation-dependent, so other compilers might do something different.
 
  • #6
why's your name written as Chatgpt? what happened? are you copying answers from chatgpt?
 
  • #7
shivajikobardan said:
why's your name written as Chatgpt? what happened? are you copying answers from chatgpt?
What day is it?
 
  • #8
shivajikobardan said:
why's your name written as Chatgpt?
Not sure, but I think that it's a prank played by the forum's owner on all the mentors as an April Fools' Day prank.

What I wrote is NOT from ChatGPT...
 
  • Like
Likes shivajikobardan
  • #9
Mark44 said:
an April Fools' Day prank.
Yah think ? :oldlaugh:
 
  • Like
Likes SammyS

FAQ: Call by reference C++ confusion

What is call by reference in C++?

Call by reference in C++ means passing the reference of an argument in the calling function to the corresponding formal parameter of the called function. This allows the called function to modify the actual argument used in the call.

How does call by reference differ from call by value in C++?

In call by value, a copy of the actual argument is passed to the function, so modifications made inside the function do not affect the original argument. In call by reference, the actual argument is passed, allowing the function to modify the original variable.

What are the benefits of using call by reference in C++?

Call by reference can improve performance by avoiding the overhead of copying large objects. It also allows functions to modify the original arguments, which can be useful for functions that need to return multiple values or modify state.

Can you provide an example of a function using call by reference in C++?

Sure! Here's a simple example:

void swap(int &a, int &b) {    int temp = a;    a = b;    b = temp;}int main() {    int x = 10, y = 20;    swap(x, y);    // Now x is 20 and y is 10    return 0;}
In this example, the swap function takes two integer references and swaps their values.

What are common pitfalls or confusions with call by reference in C++?

One common pitfall is accidentally modifying variables when not intended, as changes to the reference affect the original variable. Another confusion arises from the syntax, especially distinguishing between passing by reference and passing by pointer. It's also important to ensure that the referenced object exists for the duration of the function call to avoid undefined behavior.

Similar threads

Replies
15
Views
2K
Replies
3
Views
988
Replies
2
Views
3K
Replies
2
Views
4K
Replies
2
Views
1K
Replies
2
Views
1K
Replies
5
Views
2K
Back
Top