Solved

this

Posted on 2003-11-23
21
336 Views
Last Modified: 2010-04-01
hello all,

I need a small & easy tutorial on "this" in classes and a small example.
0
Comment
Question by:hermesc
  • 6
  • 6
  • 4
  • +4
21 Comments
 
LVL 8

Assisted Solution

by:mnashadka
mnashadka earned 150 total points
ID: 9806589
this is just a pointer to the current class.  You can use this to make sure that you're not performing self-assignment (i.e. x = x), return a reference to the current object, or send the current object into a function.  Say you have class X, the assignment operator would want to make sure that it's not assigning itself to itself (which can cause problems), you could check this by:
X &X::operator=(const X &x)
{
  if(this != &x) // Make sure that this object and the object you're assigning to it are not the same
  {
    // Perform whatever copy operations are necessary
  }
  return *this; // Return a reference to the current object
}

So when you do something like:
if((x = other_object) != some_value) // Assign it and return the object so that if can evaluate it
{
}

The other thing that this is really useful for is to send the current object as a parameter to a function:

void f(X &x)
{
  // Do something with x
}

// Now call it from inside X
void X::foo()
{
  f(*this);
}

There are a few other things that this can be useful for, but basically it's useful for anything that a pointer to the current object is needed.  Hope this helps.
0
 

Author Comment

by:hermesc
ID: 9806609
yes yes I have seen these in my books or on tutorials on the web but can you explain this in a more easy way ( I know what you have written) but I am confused in the way of coding( I have started learning classes 3 days ago )

for instance what have you done here

X &X::operator=(const X &x)
doesnt this mean that there is a X class and a object which is also X?
I will be very pleased if you send a very simple code which is using "this"
0
 
LVL 8

Expert Comment

by:mnashadka
ID: 9806642
An assignment operator will usually return a reference to itself so that you can use it (like in the if statement); the object is the lower-cased x.  It could be rewritten this way, which may be easier to read for you:
X&  X::operator=(const X &object_to_assign_it_to) // The operator= for class X that assigns an X to itself and returns itself
{
  if(this != &object_to_assign_it_to) // Make sure that the address of the current object is not the same as the address of object_to_assign_it_to
  {
    // Assign the data members
  }
  return *this; // Return a reference to the current object
}

The second example that I gave you (copied again below) is a little easier to understand, but you really need to understand the assignment operator example because that's where you usually use this

void f(X &x)
{
  // Do something with x
}

// Now call it from inside X
void X::foo()
{
  f(*this);
}
0
 
LVL 8

Expert Comment

by:_corey_
ID: 9806745
Perhaps a much more basic example will help also

Say you have a class with class variables called:

int var1;

And then you have a method in that class defined as:

void setvalue(int var1)
{
}

The parameter variable and the class variable is the same.  If you use var1 in that method, it will be using the local variable, the parameter.  So to access the class variable, you have to use the this pointer.

this.var1 = var1;

Understand?
0
 
LVL 8

Expert Comment

by:_corey_
ID: 9806747
Hah, wow my bad.  this is a pointer.  So of course in c++

this->var1 = var1;

0
 
LVL 3

Expert Comment

by:ashoooo
ID: 9807078
You really need to read your C++ book before we can teach you more about classes, this, references etc.
0
 

Author Comment

by:hermesc
ID: 9807524
corey :

this->var1 = var1;

why do i have to use pointer cant i use this.var1?
0
 
LVL 3

Expert Comment

by:ashoooo
ID: 9807536
'this' is a pointer to itself... its not an object. Thats why you need to use the -> operator and not the . operator
0
 
LVL 8

Expert Comment

by:_corey_
ID: 9807668
this isn't a pointer to itself exactly, it is a pointer to the current instance of the object.

If you had a class called MyClass and created an instance of it:

MyClass testInstance;

Then inside of the methods in MyClass, this would point to the instance that you are currently using, like:

testInstance.setvalue(5);

in the method setvalue that I showed above, this would be the pointer to testInstance internally? Get it.
0
 
LVL 3

Assisted Solution

by:RJSoft
RJSoft earned 150 total points
ID: 9808066
Consider a class the design of a bubble.

The class is the definition or "shape" of the bubble.

An instance of the class (in this example) would be the creation of a bubble.

Example.

class Bubble
{
public:
int X;
int Y;
int GetX();
int GetY();
void SetX();
void SetY();
...
};

Bubble ABubble;

ABubble is an object.

ABubble is also an object on the stack. The stack is a limmitted segment of memory. Therefore the size of the object and/or the amount of the objects (Bubbles) is limmitted.

The other area in memory that programmers use is the heap. The heap is the extended memory which is much larger than the stack.

As a program grows larger more and more objects are required. Most of the time a programmer can get away with putting most of the objects on the stack. Things such as dialog boxes and other windows items can be put on the stack because they are used only temporary. Once they are done the stack memory is then restored.

When it comes to the "this" pointer from the C++ perspective. "this" is established as a pointer because it can refference either the stack which would be a small object, or the heap which could be a large object.

The "this" pointer is a pointer that is granted to you via the C++ launguage. It is implicit.

Oddly enough though, there is really not much use for the "this" pointer from the programming perspective.

But it's implication is there none the less.

The issue is about perspective.

Basically there are 3 perspectives that you can be in at any given point of your code.

You can be in the parent perspective.

If I create an object ABubble inside of a function that belongs to another class then I have the parent perspective over the object.

Example.

class MyDialog : public CDialog
{
....
void DoSomething();
};

#include "Bubbles.h"
void MyDialog::DoSomething()
{
Bubbles ABubble;
ABubble.SetX(100);
ABubble.SetY(100);
ABubble.ShowBubble();
}//endfunc


The object ABubble is an instance of the class Bubble and BELONGS to the parent MyDialog.

So

this->ABubble.SetX(100);

is saying...

Set the member X of the object ABubble to 100 using the accessor function SetX.

Notice that "this" is now reffering to a dialog instance not the bubble. "this" is a parent over the instance of ABubble object.

Since "this" is implicit (given to us by C++ object creation) it could also have been left out.

So

ABubble.SetX(100); is the same statement.

The next perspective is the object's perspective itself. This one is kinda strange to explain except to say that "this" is the self or the object.

I think I am here, so "this" is me.

In the case of ABubble created by the class Bubble. "this" is the instance of a Bubble object.

void Bubble::SetX(int value)
{
this->X=value;
}

Think about it. An object cant create itself. For a class definition to create an object (an instance) one has to initiate it from somewhere?

Of course that is done from a parent. As in the previous parent view example.

Also once again in the above example "this->" could have been dropped because it is not needed because it is already there. Typing the "this->" is just redundancy since it is implied anyway.

The next perspective is from the child's point of view. Although this analagy is getting a little thin here.

But it is basically about manipulation of data members and or the member functions. You and others might have some difficulty seeing the difference from the perspective of the "self" and the perspective of a "child" consider the statements below.

Whatever I can use a "this" pointer to point to something that is legit also indicates a possesion of the coding location where I am coding from.

Simply using this-> in VC++ autofill brings up the members that belong to me at that location (About the only thing I ever use "this" for anyway).

But is it possible to point from the child BACK to the parent.

Yes. But not with "this".

Example.

#include "MyDialog.h"

void Bubble::ShowBubble()
{

// Hmm, I need a value that is owned by my parent instance object
// Dad owns my name and he has a public accessor function that owns it.

MyDialog *Dad =(MyDialog*)GetParent();

char Title[200];

strcpy(Title,Dad->BubbleTitle());

}

Or I could have stated

strcpy(this->Tittle,this->Dad->BubbleTittle());

Anyway, hope this helped

RJ
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Expert Comment

by:Drew_Benton
ID: 9808429
There has been a lot of posts! I hope im not repeating something that has already been stated, if i do plz forgive me :), some addition info on the use of the "this" pointer, is to gain access to a class in a free function without knowing a variable. EX:
/////////////////////////////////////
class MyClass
{
public:
   void Function1() { FreeFunction(this); }
   void SetX(int val) { X = val; }
   int GetX { return X; }

private:
   int X;
}

void FreeFunction(MyClass *Var1)
{
   Var1->SetX(25);
}

void main()
{
   MyClass MC1;
   MC1.Function1();
   cout << MC1.GetX();
}
/////////////////////////////////////

** Now you might be asking wtf would you do that for! Well an instance you would emulate that would be in MFC, making a MFC example would be to long and may stray too far away, but keep this in mind.
Hope this adds info and doesnt confuse ne1, if you really need an indepth code explaning this concept, feel free to email me, if its allowed? I;m not sure if I can post my email heh, so if its ok and some1 needs it ill post, or find a way to email whoever needs it.
0
 
LVL 3

Assisted Solution

by:ashoooo
ashoooo earned 100 total points
ID: 9808801
>> this isn't a pointer to itself exactly, it is a pointer to the current instance of the object.

There is no such thing as an instance of an object. The object itself is an instance of a class.

>>
>> If you had a class called MyClass and created an instance of it:
>>
>> MyClass testInstance;
>>
>> Then inside of the methods in MyClass, this would point to the instance that you are currently using, like:
>>
>> testInstance.setvalue(5);

Where are you demonstrating the use of 'this' in this example?

>>
>> in the method setvalue that I showed above, this would be the pointer to testInstance internally? Get it.

I've been programming in C++ for more than 6 years now and I think my understanding of C++ is good enough to know what 'this' is. When I said that 'this' is a pointer to itself, I meant that 'this' IS a pointer to THE instance of the class. I know the difference between a freaking object and a class.

Moreover, you example does not explain what 'this' is. Get it?

As for the original poster...  consider the following example code

class A
{
  void init(B * b) { b->foo(); }
}

class B
{
  A * m_a;
  B() { m_a = new A; m_a->init(this); }
  void foo() { cout << "sdf" << endl; }
  ~B() { delete m_a; }
}

...

int main()
{
  B * b = new B();
  return 0;
}

I know this is a lousy example, but I hope it helps you understand why we may need to use 'this'.
0
 
LVL 8

Accepted Solution

by:
_corey_ earned 100 total points
ID: 9808837
whatever
0
 
LVL 3

Expert Comment

by:ashoooo
ID: 9808886
Yeah, exactly. But dont try to confuse the OP's next time.
0
 
LVL 4

Expert Comment

by:n_fortynine
ID: 9808931
Experts, there is no need to flame in this thread. We all get frustrated some time. :)
Aside from that, please act professionally if you want respect from other experts. If you can defend your ideas, please by all means do so. Otherwise, simply bypassing others' comments (like saying "whatever") will not help at all.

n49.
0
 

Author Comment

by:hermesc
ID: 9809145
okey guys

final thing

#include <iostream>
using namespace std;

class Fraction {
public:
   
        return temp;
    }
    void print()
    {
        cout << num << "/" << den << endl;
    }
private:
    int num;
    int den;
};

int main() {
    Fraction a(1,2);
    Fraction b(1,4);
    Fraction c;

    a.print();
    b.print();

    c = a.add(b);

    c.print();

    return 0;
}


you know what this sources does anyway....


in this part

Fraction(int num = 0, int den = 1)
    {
        this->num = num;
        this->den = den;
    }
    Fraction add(const Fraction &rhs)
    {
        Fraction temp;
        temp.den = this->den * rhs.den;
        temp.num = rhs.den * this->num +
            this->den * rhs.num;

cant I assign num2=num; instead of this->num=num
or will be this violating accessing business?
0
 
LVL 3

Expert Comment

by:ashoooo
ID: 9810976
If, in the Fraction method, you name the first parameter anything other than 'num', then yes, you can use num=newVal. If the names are the same, they you need to use this->num.

Hope this makes sense.
0
 

Author Comment

by:hermesc
ID: 9812421
So we came up to happy end "points" :))
I just split those points to 4 parts if anyone believes which they should got more points please warn me I will arrange this in another question ( or somehow)
0
 
LVL 8

Expert Comment

by:_corey_
ID: 9812599
whatever :)

0
 
LVL 3

Expert Comment

by:ashoooo
ID: 9812752
_corey_, please accept my apologies.
0
 
LVL 8

Expert Comment

by:_corey_
ID: 9812860
Nah, I shouldn't have been nit-picking either, I just thought that saying "pointer to itself" might confuse someone as I had seen it before, although my response was not technically accurate I suppose, I just didn't think the words mattered.

The whatever wasn't aggressive, just saying as long as he understand what it is a pointer to, I don't claim to be technically accurate all the time!
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now