This

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
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.
I can't understand I don't know operators yet I haven't reach them
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
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.
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.
I know classes but i can't understand what those return *this mean
closed account (zb0S216C)
It means that you're returning the class pointed to by this.

Wazzak
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
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;
}
Thanks I got it
Topic archived. No new replies allowed.