Call by reference C++ confusion

  • Context: Comp Sci 
  • Thread starter Thread starter shivajikobardan
  • Start date Start date
  • Tags Tags
    C++ Confusion Reference
Click For Summary
SUMMARY

The discussion focuses on the differences between call by value, call by pointer address, and call by reference in C++. It emphasizes that C++ allows for reference parameters, which provide similar functionality to pointers but with different semantics. The participants clarify that the overloaded extraction operator (<<) requires a reference to an ostream object, which is crucial for proper memory management and function behavior. The conversation also highlights the importance of understanding these concepts to avoid common pitfalls in C++ programming.

PREREQUISITES
  • Understanding of C++ function call types: call by value, call by pointer address, and call by reference.
  • Familiarity with operator overloading in C++, specifically the extraction operator (<<).
  • Basic knowledge of memory management in C++.
  • Proficiency in using the C++ standard library, particularly the iostream header.
NEXT STEPS
  • Study C++ operator overloading techniques, focusing on the extraction operator (<<).
  • Learn about memory management and references in C++, including the implications of using references versus pointers.
  • Explore practical examples of call by value, call by pointer, and call by reference in C++.
  • Investigate the assembly code generated by different C++ compilers for function calls to understand optimization differences.
USEFUL FOR

Software developers, particularly those working with C++, educators teaching programming concepts, and anyone looking to deepen their understanding of function call mechanisms and memory management in C++.

shivajikobardan
Messages
637
Reaction score
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
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:
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.
 
thank you for the reply. I need to learn about call by address and call by reference first.
 
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::count; 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);
	count << "num = " << num << endl;

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

	num = 5;        // Reset num.
	// Call by reference can change the value of its argument.
	CallByRef(num);
	count << "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.
 
why's your name written as Chatgpt? what happened? are you copying answers from chatgpt?
 
shivajikobardan said:
why's your name written as Chatgpt? what happened? are you copying answers from chatgpt?
What day is it?
 
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   Reactions: shivajikobardan
Mark44 said:
an April Fools' Day prank.
Yah think ? :oldlaugh:
 
  • Like
Likes   Reactions: SammyS

Similar threads

  • · Replies 15 ·
Replies
15
Views
2K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 2 ·
Replies
2
Views
5K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 2 ·
Replies
2
Views
6K
  • · Replies 5 ·
Replies
5
Views
3K