Why do I need the this pointer in C++?

  • Context: C/C++ 
  • Thread starter Thread starter yungman
  • Start date Start date
Click For Summary

Discussion Overview

The discussion revolves around the use and necessity of the "this" pointer in C++, particularly in the context of class member functions and operator overloading. Participants explore the implications of having a single copy of member functions shared among class instances and the role of "this" in various coding scenarios.

Discussion Character

  • Exploratory
  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • Some participants question the claim that all objects share a single copy of member functions, seeking clarification on this point.
  • There is a discussion about the necessity of the "this" pointer, with some arguing it adds confusion while others suggest it is essential for certain operations, such as passing pointers to functions.
  • Participants express differing views on operator overloading, with some seeing it as elegant and useful, while others believe it complicates code unnecessarily.
  • One participant provides an example of a class representing a 3-D vector and discusses the overloaded assignment operator, questioning how it could function without the "this" pointer.
  • There is a mention of the importance of understanding the "this" pointer even if one chooses not to use it, highlighting its relevance in reading and maintaining code.
  • Some participants suggest that operator overloading should be used judiciously, particularly in contexts where it enhances clarity and functionality, such as with vectors or strings.
  • One participant raises a hypothetical scenario about implementing a COMPLEX data type, emphasizing the need for operator overloading in custom data types.

Areas of Agreement / Disagreement

Participants express a mix of agreement and disagreement regarding the necessity and clarity of the "this" pointer and operator overloading. The discussion remains unresolved, with multiple competing views on the utility and elegance of these concepts.

Contextual Notes

Some participants note that operator overloading can lead to confusion if overused, and there are concerns about the potential for creating code that is difficult to understand and maintain. The discussion reflects varying levels of comfort and familiarity with these concepts among participants.

Who May Find This Useful

This discussion may be useful for C++ learners, programmers interested in object-oriented programming, and those exploring the implications of operator overloading and the "this" pointer in their code.

  • #31
Vanadium 50 said:
What is the purpose of the & after Length? Why do you want it?
There IS a purpose to returning the LHS as a reference in assignment operator overloads (like +=), but not simple binary operators like +.

How do I know this? Because I looked it up. I have been programming (not in C++ obviously) for over 40 years without the benefit of this knowledge, and I do not expect ever to need it again.

Why someone would spend time learning about operator overloading (or teaching it for that matter) in a first introduction to C++ is beyond me.
 
Technology news on Phys.org
  • #32
pbuk said:
There IS a purpose to returning the LHS as a reference in assignment operator overloads (like +=), but not simple binary operators like +.

Oh, I am sure there is a purpose. There is a purpose to almost everything in C++, except maybe goto. :wink:

pbuk said:
How do I know this? Because I looked it up.

Well that's just crazy talk.o0)

Anyway, I was obviously unclear. My question was less "what is this structure used for?" and more "what are you trying to accomplish with this code?" The answer is

yungman said:
So I added the & just for the hell of it and see what happens!

Followed by sending us to figure out what was going without telling us the compiler threw a warning, and making the incredible claim that it worked anyway. I mean, it could have worked, in the sense that jumping to a random spot in memory could work, but it's incredibly unlikely.

pbuk said:
Why someone would spend time learning about operator overloading (or teaching it for that matter) in a first introduction to C++ is beyond me.

I agree. To be fair to Mr. Gaddis, it's only three paragraphs in the entire book.
 
  • #33
pbuk said:
Why someone would spend time learning about operator overloading (or teaching it for that matter) in a first introduction to C++ is beyond me.
I think that it is too commonly used to be skipped. I tend to think that it is overused, but even with reduced, judicious use, it would appear a lot.
 
  • #34
FactChecker said:
I think that it is too commonly used to be skipped. I tend to think that it is overused

I agree. I also don't think Gaddis does a very good job here - he does not emphasize the most used (and IMHO best) use case: comparison operators. Is "van der Meer" before or after "Van Cleef"?
 
  • #35
Mark44 said:
warning C4172: returning address of local variable or temporary: temp

Doing this in very simple cases will work as expected. This leads one to think that what they are doing is safe. Which leads to nearly impossible to debug code.

BoB
 
  • #36
jtbell said:
......

The first version returns a reference to a local variable (a variable that is declared inside operator+()). What happens to local variables after operator+() finishes and you return to main(), or to whatever function called operator+()?
Both function return temp object and copy into L3. The function ended and destroyed, but the temp is being returned back.
 
  • #37
Vanadium 50 said:
I agree. I also don't think Gaddis does a very good job here - he does not emphasize the most used (and IMHO best) use case: comparison operators. Is "van der Meer" before or after "Van Cleef"?
That might be true if C++ had a 'spaceship' operator, but it doesn't and so we have std::string::compare.
 
  • #38
pbuk said:
if C++ had a 'spaceship' operator

Just wait a bit. That's coming in C++20.

BoB
 
  • #39
I don't think C++ needs a spaceship operator to discuss overloading as a way to put classes (not just strings) in a sequence. The existing string operators do what need to be done, although it's a bit opaque exactly how. (Is "van der Meer" > "Van Cleef"? Is the answer the same on an EBCDIC machine?)

While I hold that overloading comparison operators makes more sense than many others - I am more prepared to accept red > pink than ++pink being red - I don't think I have ever done this, and am not likely to do so. The advantage of this approach is that it gives you The One True Sort Order. The disadvantage is that it gives you The One True Sort Order, and if things are sufficiently ambiguous that the programmer feels necessary to define one, she probably wants the ability to see how things work under different conditions, if only for testing.
 
  • #40
This is returning a dangling reference to temp, a variable which no longer exists after the function returns. The result is undefined behavior. If it works in your case, it's only due to luck: the reference is pointing to memory that may still happen to contain temp's value, but this is not guaranteed, and you should not be accessing this memory.
Code:
         Length& operator+(const Length&right)
            { Length temp;  temp.Len = Len + right.Len;    return temp; }
You need to return a value, not a reference:
Code:
         Length operator+(const Length&right)
            { Length temp;  temp.Len = Len + right.Len;    return temp; }
 
  • Like
Likes   Reactions: yungman
  • #41
jbunniii said:
This is returning a dangling reference to temp, a variable which no longer exists after the function returns. The result is undefined behavior. If it works in your case, it's only due to luck: the reference is pointing to memory that may still happen to contain temp's value, but this is not guaranteed, and you should not be accessing this memory.
Code:
         Length& operator+(const Length&right)
            { Length temp;  temp.Len = Len + right.Len;    return temp; }
You need to return a value, not a reference:
Code:
         Length operator+(const Length&right)
            { Length temp;  temp.Len = Len + right.Len;    return temp; }
Thanks for the reply, that really clears it up for me. It must be just luck that the memory is not erased.

Thanks
 

Similar threads

  • · Replies 19 ·
Replies
19
Views
6K
Replies
5
Views
2K
Replies
12
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
Replies
5
Views
2K
Replies
89
Views
6K
Replies
18
Views
3K
Replies
53
Views
5K
  • · Replies 23 ·
Replies
23
Views
3K