This...

Can anyone please explain how 'this' is used. I do not want the explanation in this sites tut
Last edited on
'this' is the memory address of the object of the class.
Why does this code fail me?
Error: |40| error: invalid use of 'this' in non-member function|


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
36
37
38
39
40
41
#include <iostream>
//----------------------namespaces-----------------------------------------------
using namespace std;
//------------globals/functions'n'classes-prototypes-----------------------------
class C1;
class C2;

//-------------------------code--------------------------------------------------

class C1{virtual void dummy(){}};
class C2:public C1
{
    public:
        void check(C2*);
}obj1;


int main()
{
    C2 *p_obj2;

    try
    {
        C1 *p_obj1=new C1;
        p_obj2=static_cast<C2*>(p_obj1);

        if(p_obj2==0) cout<<"Failed...what this is pointing to is not a full object!!!";
        else cout<<"Great...working!!!";
    }
    catch(exception& e)
    {
        cout<<"Exception caught: "<<e.what();
    }
    obj1.check(&obj1);
    cin.get();
}

void check(C2 temp_obj)
{
    if(temp_obj==this) cout<<"Fine";
}
Last edited on
This code should explain everything :

1
2
3
4
5
6
7
8
9
10
11
12
13

#include <iostream>

class Foo {
public:
    void print_my_address() { std::cout << this << std::endl; }    
};

int main() {
    Foo x;
    std::cout << &x << std::endl;
    x.print_my_address();
}


this is a way a member function can refer to the object it operates on.

EDIT: in your code you forgot to add the C2:: prefix before the check function on line 38.
Last edited on
Thank you all!!!
closed account (zb0S216C)
Aceix wrote:
"Why does this code fail me?"

Because you're using this outside the class context. It stems from how C++ implements member functions. Implicitly, all member functions contain a parameter, called this, which may be declared as ClassName * const this. When you invoke a member function from an object, the compiler will pass the address of the object you're calling the member function from to this of the member function you're calling. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct Sample
{
    void function(); // Compiler will add "Sample * const this" as a parameter.
};

int main()
{
    Sample sample;
    
    sample.function();
    // Here, the compiler will take the address of "sample" and give
    // it to the "this" parameter of "function()". "function()" will take
    // the address, and refer to "sample" with it.
}

Outside the class context, this is meaningless.

Wazzak
Last edited on
Topic archived. No new replies allowed.