Passing by reference and operator overloading (2023)

In this talk, we gave an overview of some advanced features in C++ that Clangauge doesn't offer.

passed as a reference

Remember that one of the reasons you might pass a pointer to a function is that you want to allow that function to change the value of what you passed it. For example, here's a super simple function to increase the value of the first number by 3:
void add3(int* xptr) { *xptr = *xptr + 3;}
This works, but can be a bit annoying since we have to use the * dereference operator everywhere in our function. Also, we must remember to add the operator address when calling this function, such as:
int a = 10;add3(&a);add3(&a);// now a is equal to 16
Because pointers can be difficult and sometimes "dangerous" to use, C++ tries to avoid some of the situations in which we might need to use them. The answer in this case is to use a reference variable as a parameter to the add3 function, like this:
void add3(int& x) { x = x + 3;}
Specifying a reference type is similar to specifying a pointer type, except instead of a *, you use an & with the type. This means that the x passed to the function is a reference to the variable on which the function is called. Changing x in the function when x is a reference variable also changes the original value!
int a = 10;add3(a); // works now, no pointers needed!add3(a); // now a = 16
Pass by reference is also used in C++ to return multiple values ​​from a function (by passing multiple arguments by reference) or to avoid copying something that is large or doesn't make sense to copy.

Passing streams for reference

As you know, copying is not allowed for streams. Then,we can use streamobjects (bothour enemyeFlow) for reference.Compared to using Pass by Address, we can write the same code much easier using Pass by Reference.
int readtime(istream&); readtime(istream& in){int h, m, s;char c;in >> h >> c >> m >> c >> s;return h*3600 + m* 60+;}

As you can see, the function reads the elapsed time from ourhh:mm:ssFormat.

With these definitions I can say

(Video) Example of class, pass by reference, operator overloading, portioning an int - C++ - ENGR 2304

int k = read time (cin);
when I have to read from the keyboard for a while.

monitoring: Bothcinand everythingifstreamObjects can be passed by referenceFlow.Therefore I can also say:

ifstream fin("data.txt");int m = readtime(fin); // pass fin to istream as a reference
... if I have to read in betweenfrom a file Daten.txtwith the same functionreading time.

It would be wonderful to have a functionreading timethat can happen to anyonecinorfinRead in the elapsed time as argumenthh:mm:ssformat and return in seconds.

(Video) Constant Reference Parameters and Operator Overloading

operator overload

C++ allows the programmer to create new types that actually behave like the built-in types, which means that the usual operators like *, <, ++ work with the new types and I/O with << and >>, and short .

Although this isn't a main topic for this course, I want to address it so you understand that we really can create new types in C++ if we want to. Also, I should note that this is why + and >> etc work with C++Fragmentobjects. The string library implementers have defined all of these operators for their good string type.

simple program

Let's write a program that draws a course this way.
  1. They start at (0,0).
  2. Then you can get into "movements". A move of (-2,4) means a move 2 units down and 4 units to the right of your current position.
  3. The user continuously enters moves until finally entering one.qexit.
First solution. my first solutionIt's a fairly simple program.
The meat of the program is:
operator overload.While it may be simple, it would be nice to be able to write the function as ifpoint it outwere an inline type, meaning I could add dotspemsayingp + m.
// initialize stream OUT("out.txt");point p,m;p.x = p.y = m.x = m.y = 0;// get moves and write movesdo { // calculate new position p from move m p.x = p.x + m.x ; p.y = p.y + my; // Write move OUT << p.x << '\t' << p.y << endl;}while(getmove(m,cin));
// Initialisierung -- igual a beforeofstream OUT("out.txt");point p,m;p.x = p.y = m.x = m.y = 0;do { p = p + m; //* ** OLHE AQUI* ** OUT << p.x << '\t' << p.y << endl;}while(getmove(m,cin));
It wouldn't change what I could achieve, but it would add some "syntactic sugar" to sweeten the program a bit.

prototype and definition?

To do this, we need to be able to tell the compiler whatp + mmeans forpoint it outobjectspem. This is very easy once you understand the following:

a+bis exactly the same as the function callOperator+(a,b)I'm C++.


So if you want to tell the compiler something+means for twopoint it outobjects, you must define the functionoperator+(point a, point b)--- This isoverloada+operator forpoint it outs. The prototype is clear:

(Video) Buckys C++ Programming Tutorials - 39 - Pass by Reference with Pointers

point operator+(point a, point b); least I hope it's clear that if we add two points we have to return one point. The function definition is... like any other function definition:
point operator+(point a, point b){ point S; S.x = a.x + b.x; S.y = a.y + b.y; returns S ;}

Using the overloaded operator

So with that supplement, here it ismy second versionfrom the program. Well, the syntactic sugar might not be worth the trouble here, but you'll probably use thosepoint it outstruct over and over again, and you'll like that you can addpoint it outs. Wouldn't it be good to stop themFocuswork like this:
point midpoint(point a, point b){ return (a + b)/2.0;}

Overload other operators

"Operator overload" is the term used to define versions of C++ operators for the new frameworks we're defining. Generally if you have a printoutA PB, where "Π" represents an operator, this corresponds to a function callOperatorΠ(A,B).So to subtract two points, we would define
point operator (point A, point B);
... and compare two points with less than we defined
operator bool<(point A, point B);
...or multiplying a point (left) by a real number (right) we would define
dot operator*(dot A, double w);

Scalars Division operator

Well, in addition to the definitionoperator +for twopoint it outObjects, what else do you need? Spring,(a + b)is an object of typepoint it out, and I divide it by an object of typeDouble, so I have to adjustoperator/(period, double). What kind of object do you want to return here?
PointOperator/(PointP, duple z){ PointQ; Q.x = P.x/z; Q.y = P.y / z; gib Q back;}

E/A und Overhead

Just to complete our examples, see how to overload << and >>.
Operator istream&>>(istream &in, Punkt &A){ char c; return in >> c >> A.x >> c >> A.y >> c;}ostream& operator<<(ostream &out, point A){ return out << '(' << A.x << ',' << A.y < <')';}
The prototypes for these two should really make sense. For example, earlier we talked about howcin >> xreally rates back tocin.

However, this is new"Return by reference".

Normally, when a function returns an object X, the object returned in the calling function is a copy of that X. By using return by reference, we're saying, "No, I want the calling function to get itexactly the same item I returned, not a copy". Of course, this can only be done with something that doesn't go out of scope and dies at the end of the function call.

To summarize all these overloaded functions, consider this example:dot.hedot.cpp.

(Video) C++ Operator Overloading beginner to advanced (in-depth explanation)

practical problems

  1. Incrementing a military watch(You may preferthis solution.) This is a simple example of passing by reference that modifies your argument.
  2. Reading binary numbersHere's a simple example where we use pass-by-reference to avoid making a copy of an istream object.


(The Cherno)
2. Pass By Reference | C Programming Tutorial
(Portfolio Courses)
3. Operator Overloading
4. Passing vectors into functions by value and by reference (C++ programming tutorial)
5. Stream Insertion | Stream Extraction Operator Overloading In C++
6. C++ reference parameters and overload functions
(Coding with Chapa)
Top Articles
Latest Posts
Article information

Author: Patricia Veum II

Last Updated: 02/20/2023

Views: 5773

Rating: 4.3 / 5 (64 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Patricia Veum II

Birthday: 1994-12-16

Address: 2064 Little Summit, Goldieton, MS 97651-0862

Phone: +6873952696715

Job: Principal Officer

Hobby: Rafting, Cabaret, Candle making, Jigsaw puzzles, Inline skating, Magic, Graffiti

Introduction: My name is Patricia Veum II, I am a vast, combative, smiling, famous, inexpensive, zealous, sparkling person who loves writing and wants to share my knowledge and understanding with you.