This

Aug 17, 2011 at 6:21am
I can't the usage if this in c++ actually when we write return *this at the end of a function please explain it for me
Aug 17, 2011 at 6:35am
in C++, the "this" keyword is a pointer to the current instance of the class in a function in which the "this" is used. Doing something like:
 
return (*this);


basically returns the instance of the class, "*" is the dereference operator and "this" is the pointer to the instance.
Aug 17, 2011 at 9:52am
I can't understand I don't know operators yet I haven't reach them
Aug 17, 2011 at 9:55am
you don't know operators yet? I can't think of many programs you could make without using any operators...

If you don't understand pointers yet read this http://cplusplus.com/doc/tutorial/pointers/

this is just a pointer to the object that a function is working on, have you learned classes yet? If not then the this keyword won't make any sense. Work your way through these to fill the gaps in your knowledge http://cplusplus.com/doc/tutorial/
Last edited on Aug 17, 2011 at 10:00am
Aug 17, 2011 at 11:22am
closed account (1vRz3TCk)
quirkyusername wrote:
you don't know operators yet? I can't think of many programs you could make without using any operators..
Using them and knowing that they are called operators are two different things.
Aug 17, 2011 at 1:22pm
Using them and knowing that they are called operators are two different things.

That was my point, and why I linked him to a tutorial on pointers and not operators.
Aug 17, 2011 at 8:39pm
I know classes but i can't understand what those return *this mean
Aug 17, 2011 at 9:01pm
closed account (zb0S216C)
It means that you're returning the class pointed to by this.

Wazzak
Aug 17, 2011 at 11:10pm
so how can it help us with using that would you understood me with an example that what usage this have that with other pointers we can't do it in return *this
Aug 17, 2011 at 11:45pm
closed account (D80DSL3A)
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;

class Complex
{
    double real;
    double imag;

    public:
    // constructor
    Complex(double Real, double Imag): real(Real), imag(Imag){}

    // return the modified Complex object
    Complex conjugate()
    {
        imag *= -1.0;
        return *this;
    }

    // display the Complex number
    void print(){ cout << "(" << real << ", " << imag << ")"; }
};


int main()
{
    Complex z(2.0, 3.0);
    z.print();

    // z is modified by conjugate() then the returned instance calls the print()
    z.conjugate().print();

  cout << endl;
  return 0;
}
Aug 18, 2011 at 12:50am
Thanks I got it
Topic archived. No new replies allowed.