943,982 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Marked Solved
  • Views: 9835
  • C++ RSS
Nov 28th, 2006
0

This Pointer / Copy Constructor

Expand Post »
I've read my book, and there's some topics where I feel weak about:

- inline functions
- static members
- this pointer
- copy constructor

I've read some tutorials online, but they use some complicated code, and I'm a beginner programmer, so I can't understand their explanations.

Just wondering, if anyone could summarize (tell me their uses) and give me simple examples of those. That would really help me understand what I'm learning .. especially the this pointer! Thanks!
Similar Threads
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
aznballerlee is offline Offline
73 posts
since Oct 2006
Nov 28th, 2006
0

Re: This Pointer / Copy Constructor

Here was also an example of the this pointer that I didn't understand: (We're transitioning from structs to class)

C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct Target
  5. {
  6. private:
  7. int pos;
  8. string history;
  9. public:
  10. void init();
  11. bool move(char dir);
  12. void animateHistory()const;
  13. };
  14.  
  15. void init (Target *tp)
  16. {
  17. tp -> pos = 0;
  18. tp -> history = "";
  19. }
  20.  
  21. bool move (Target* tp, char dir)
  22. {
  23. switch (dir)
  24. {
  25. default:
  26. return false;
  27. case 'L':
  28. tp -> pos--;
  29. break;
  30. case 'R':
  31. tp -> pos++;
  32. break;
  33. }
  34. tp -> history += dir;
  35. return true;
  36. }
  37.  
  38. void animateHistory (const Target* tp)
  39. {
  40. for (int k =0; k != tp -> history.size(); k++)
  41. cout << tp -> history[k] << endl;
  42. }
  43.  
  44. int main()
  45. {
  46. Target t;
  47. t.init();
  48. t.move('R');
  49. t.move('R');
  50. t.animateHistory();
  51. }
became this:
C++ Syntax (Toggle Plain Text)
  1. struct Target
  2. {
  3. private:
  4. int pos;
  5. string history;
  6. public:
  7. void init();
  8. bool move(char dir);
  9. void animateHistory()const;
  10. };
  11.  
  12. void Target::init ()
  13. {
  14. this -> pos = 0;
  15. this -> history = "";
  16. }
  17.  
  18. bool Target::move (char dir)
  19.  
  20. {
  21. switch (dir)
  22. {
  23. default:
  24. return false;
  25. case 'L':
  26.  
  27. this -> pos--;
  28. break;
  29. case 'R':
  30. this -> pos++;
  31. break;
  32. }
  33. this -> history += dir;
  34. return true;
  35. }
  36. void Target::animateHistory () const
  37. {
  38. for (int k =0; k != this -> history.size(); k++)
  39. cout << this -> history[k] << endl;
  40. }
  41. int main()
  42. {
  43. Target t;
  44. t.init(); // &t will be passed as the value of the "this" pointer
  45. t.move('R'); // &t will be passed as the value of the "this" pointer
I don't understand why we had no parameters (for the second code) for some of the public member functions, or rather how Target* tp "disappeared" from each parameter. What is the cause, and why can we do that?

from here (part of 2nd code):

C++ Syntax (Toggle Plain Text)
  1. public:
  2. void init();
  3. bool move(char dir);
  4. void animateHistory()const;
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
aznballerlee is offline Offline
73 posts
since Oct 2006
Nov 28th, 2006
0

Re: This Pointer / Copy Constructor

Ok, I figured I'll just point you to a site and then offer my explanation as well. Here's a good link.
http://cplusplus.com/doc/tutorial/classes2.html
This link talks about the "this" keyword and static member data/functions of a class.

This "this" keyword just means "this class".

A Copy Constructor is a special kind of constructor. For example, lets say you have a simple linked list and you want to make a complete copy of it. Dynamic memory and all. Then you would need to make a copy constructor to do this. You could also do operator overloading for the '=' operator, but that's for a later discussion.

There are two types of copying. There's shallow copying where it just copies the members functions and member data and does not copy dynamic data and there's deep copying which does copy dynamic data. Here's a quick picture I whipped up in mspaint to better illustrate my point.
http://img297.imageshack.us/img297/240/copyao2.png

Copy constructors are REALLY useful when you have an array of pointers pointing to some dynamic data and you want to make a copy of it for various operations and such.

Now on to inline functions. Lets say you have two functions in your program. You have int main() and you have float FindAverage(/* your parameter list */). Now let's say you want to inline FindAverage(). What inlining a function does is tell the compiler to replace all function call of FundAverage with the code inside FindAverage. Here's some before and after compiler inline optimization.

This is the code before compiler optimization.
C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. inline void FindAverage(int, int, int&);
  6.  
  7. int main()
  8. {
  9. int exam1;
  10. int exam2;
  11. int average;
  12.  
  13. cout << "Enter exam1 score: ";
  14. cin >> exam1;
  15. cout << endl << "Enter exam2 score: ";
  16. cin >> exam2;
  17.  
  18. FindAverage(exam1, exam2);
  19.  
  20. cout << "Average has been computed" << endl;
  21.  
  22. return 0;
  23. }
  24.  
  25. inline void FindAverage(int exam1, int exam2, int& avg)
  26. {
  27. avg = (exam1 + exam2)/2;
  28. }

This is how the compiler would treat the code.
C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7. int exam1;
  8. int exam2;
  9. int average;
  10.  
  11. cout << "Enter exam1 score: ";
  12. cin >> exam1;
  13. cout << endl << "Enter exam2 score: ";
  14. cin >> exam2;
  15.  
  16. avg = (exam1 + exam2)/2; // The code for FindAverage has
  17. // been substituted in it's place.
  18.  
  19. cout << "Average has been computed" << endl;
  20.  
  21. return 0;
  22. }

The benefits for this is that when you do a normal function call it pushes the current data to the stack and then jumps to the function being called. Afterwards it returns after destroying any data that the function created and pops the data from the stack. So basically the only advantage it has is in function overhead. Using inline doesn't require the stack. However it's only useful for small functions. It should only be used when the code from compiling is faster than the required overhead. It's just another technique for optimization of code.

Here's some links that will explain this concept. It probably does a better way of explaining it then I do.
http://cplusplus.com/doc/tutorial/functions2.html

[edit]I just noticed my explanation and code for inline function has some differentces but I think you should be able to get the point of it. Hope this helps![/edit]
Last edited by oRg; Nov 28th, 2006 at 11:08 pm.
oRg
Reputation Points: 22
Solved Threads: 1
Newbie Poster
oRg is offline Offline
15 posts
since Feb 2005
Nov 28th, 2006
0

Re: This Pointer / Copy Constructor

Here was also an example of the this pointer that I didn't understand: (We're transitioning from structs to class)

C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct Target
  5. {
  6. private:
  7. int pos;
  8. string history;
  9. public:
  10. void init();
  11. bool move(char dir);
  12. void animateHistory()const;
  13. };
  14.  
  15. void init (Target *tp)
  16. {
  17. tp -> pos = 0;
  18. tp -> history = "";
  19. }
  20.  
  21. bool move (Target* tp, char dir)
  22. {
  23. switch (dir)
  24. {
  25. default:
  26. return false;
  27. case 'L':
  28. tp -> pos--;
  29. break;
  30. case 'R':
  31. tp -> pos++;
  32. break;
  33. }
  34. tp -> history += dir;
  35. return true;
  36. }
  37.  
  38. void animateHistory (const Target* tp)
  39. {
  40. for (int k =0; k != tp -> history.size(); k++)
  41. cout << tp -> history[k] << endl;
  42. }
  43.  
  44. int main()
  45. {
  46. Target t;
  47. t.init();
  48. t.move('R');
  49. t.move('R');
  50. t.animateHistory();
  51. }
became this:
C++ Syntax (Toggle Plain Text)
  1. struct Target
  2. {
  3. private:
  4. int pos;
  5. string history;
  6. public:
  7. void init();
  8. bool move(char dir);
  9. void animateHistory()const;
  10. };
  11.  
  12. void Target::init ()
  13. {
  14. this -> pos = 0;
  15. this -> history = "";
  16. }
  17.  
  18. bool Target::move (char dir)
  19.  
  20. {
  21. switch (dir)
  22. {
  23. default:
  24. return false;
  25. case 'L':
  26.  
  27. this -> pos--;
  28. break;
  29. case 'R':
  30. this -> pos++;
  31. break;
  32. }
  33. this -> history += dir;
  34. return true;
  35. }
  36. void Target::animateHistory () const
  37. {
  38. for (int k =0; k != this -> history.size(); k++)
  39. cout << this -> history[k] << endl;
  40. }
  41. int main()
  42. {
  43. Target t;
  44. t.init(); // &t will be passed as the value of the "this" pointer
  45. t.move('R'); // &t will be passed as the value of the "this" pointer
I don't understand why we had no parameters (for the second code) for some of the public member functions, or rather how Target* tp "disappeared" from each parameter. What is the cause, and why can we do that?

from here (part of 2nd code):

C++ Syntax (Toggle Plain Text)
  1. public:
  2. void init();
  3. bool move(char dir);
  4. void animateHistory()const;
The first example doesn't compile. It's got all sorts of errors in it, doesn't even make sense in some parts, and looks kind of crazy.

The second code example works, and it's basically using this-> inside of its member functions in front of all the variables it wants to modify, however there's no real need to do this. The following will work just as well:
C++ Syntax (Toggle Plain Text)
  1. struct Target
  2. {
  3. private:
  4. int pos;
  5. string history;
  6. public:
  7. void init();
  8. bool move(char dir);
  9. void animateHistory()const;
  10. };
  11.  
  12. void Target::init ()
  13. {
  14. pos = 0;
  15. history = "";
  16. }
  17.  
  18. bool Target::move (char dir)
  19.  
  20. {
  21. switch (dir)
  22. {
  23. default:
  24. return false;
  25. case 'L':
  26.  
  27. pos--;
  28. break;
  29. case 'R':
  30. pos++;
  31. break;
  32. }
  33. history += dir;
  34. return true;
  35. }
  36. void Target::animateHistory () const
  37. {
  38. for (int k =0; k != history.size(); k++)
  39. cout << history[k] << endl;
  40. }
  41. int main()
  42. {
  43. Target t;
  44. t.init(); // &t will be passed as the value of the "this" pointer
  45. t.move('R'); // &t will be passed as the value of the "this" pointer
  46. return 0;
  47. }
All I did was remove the this-> code. The most useful thing for the this pointer is storing the address of the current instance on an object. For modifying variables, nah...

Hope this helps
Team Colleague
Reputation Points: 2240
Solved Threads: 338
Vampirical Lurker
John A is offline Offline
5,055 posts
since Apr 2006
Nov 29th, 2006
0

Re: This Pointer / Copy Constructor

So would you say that for classes, the
C++ Syntax (Toggle Plain Text)
  1. this pointer
is not useful unless we use pointers?

Also, someone said about passing stuff implicitly, so we have the () empty parameter. Can you explain that? That's confusing me a lot.
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
aznballerlee is offline Offline
73 posts
since Oct 2006
Nov 29th, 2006
0

Re: This Pointer / Copy Constructor

the "this" keyword is a pointer to the class in which it's used. For example:
C++ Syntax (Toggle Plain Text)
  1. this->idNum
Is referring to the idNum data of the class your writing for.

So to answer your question, yes you would only need the "this" keyword if your working with pointers because it is essentially a pointer. It's the pointer of a class pointing to itself, if that makes any sense to you.
oRg
Reputation Points: 22
Solved Threads: 1
Newbie Poster
oRg is offline Offline
15 posts
since Feb 2005
Nov 29th, 2006
0

Re: This Pointer / Copy Constructor

Click to Expand / Collapse  Quote originally posted by oRg ...
the "this" keyword is a pointer to the class in which it's used. For example:
C++ Syntax (Toggle Plain Text)
  1. this->idNum
Is referring to the idNum data of the class your writing for.

So to answer your question, yes you would only need the "this" keyword if your working with pointers because it is essentially a pointer. It's the pointer of a class pointing to itself, if that makes any sense to you.
Looks like you are using the words class and object interchangeably.

Correction:
Quote ...
The this pointer is a pointer accessible only within the nonstatic member functions of a class, struct, or union type. It points to the object for which the member function is called. Static member functions do not have a this pointer.

An object's this pointer is not part of the object itself; it is not reflected in the result of a sizeof statement on the object. Instead, when a nonstatic member function is called for an object, the address of the object is passed by the compiler as a hidden argument to the function.
Super Moderator
Featured Poster
Reputation Points: 3233
Solved Threads: 720
Failure as a human
~s.o.s~ is offline Offline
8,872 posts
since Jun 2006
Nov 29th, 2006
0

Re: This Pointer / Copy Constructor

lol, yeah. It's a bad habit of mine that I'm trying to get out of. I understand the difference (an object is an instance of a class), but for some reason I have momentary brain farts of something. :p
oRg
Reputation Points: 22
Solved Threads: 1
Newbie Poster
oRg is offline Offline
15 posts
since Feb 2005

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Should be an easy question to answer
Next Thread in C++ Forum Timeline: factors - 2 functions





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC