tags:

views:

149

answers:

2
+2  Q: 

java "this" in c++

I'm in a function in java and I create a new Object passing "this" as paramter:

class AClass { 
    AClass(TestClass testClass) { }
}

class TestClass {
    AClass doSomething()
    {
        return new AClass(this);
    }
}

How to do That in C++?

Should be:

class AClass {
    AClass(TestClass* testClass) { }
};

class TestClass {
    AClass* doSomething()
    {
        return new AClass(*this);
    }
};

Should I pass *this, or &this?

+3  A: 

It depends. You're probably looking for this:

class AClass { 
    AClass(TestClass& testClass) { } 
}; 

class TestClass { 
    AClass doSomething() 
    { 
        return AClass(*this); 
    } 
}; 

To use it in C++:

TestClass testClass;
AClass aClass = testClass.doSomething();

But what are you really trying to do? Unlike Java, C++ makes the distinction between values and references explicit. You should really read a good beginner's C++ book, as James McNellis has suggested.

The distinction between values/references/pointers that C++ makes is fundamental to the language and failing to respect that will lead to disaster. Again, please pick up a C++ book.

In silico
by this way you're copying the TestClass passing *this? So the constructor is being called like that: AClass(TestClass testClass) { }but if I put "return " the AClass constructor should be: AClass(TestClass *testClass) { } ?
okami
In silico
I want to pass the TestClass as reference
okami
@okami - I have modified my answer so that a reference to `TestClass` is passed instead of a pointer. But please, I implore you to pick up a C++ book and read it (see http://stackoverflow.com/questions/388242/the-definitive-c++-book-guide-and-list). I don't mean to be offensive, but C++ is very different from Java and treating C++ like Java will not help you in the long run.
In silico
`this` is of type `TestClass *` so doing `AClass(this)` will call `AClass(TestClass *testClass)`.
Niki Yoshiuchi
ok I'll take a look at a C++ book, thanks!
okami
+1  A: 

Given the declaration you wrote

class AClass {
    AClass(TestClass* testClass) { }
};

You need to pass a pointer, so you'd use this. However, it's generally preferred in C++ to use references (especially const references) instead of pointers, so you'd declare AClass as:

class AClass {
    AClass(const TestClass& testClass) { }
};

To which you would pass *this.

Now, there are situations in which the pointer version is preferred. For example, if testClass were allowed to be NULL (you can't have null references). Or if testClass were stored in a std::vector or similar data structure. (You can't have arrays of references.)

dan04
very good, const is very useful in c++ much more than java "final"
okami