Possible Duplicate:
How to pass objects to functions in C++?
Operator & and * at function prototype in class
#include <iostream>
using namespace std;
class C {
public:
int isSelf (C& param);
};
bool C::isSelf (C& param)
{
if (¶m == this) return true;
else return false;
}
int main () {
C a;
C* b = &a;
cout << boolalpha << b->isSelf(a) << endl;
return 0;
}
This code works. But it seems to me that b->isSelf(a) should really be b -> isSelf(&a) because isSelf expects an address of type C?!
[EDIT]
Additional questions:
1) Is there a way to implement this isSelf function using pass by value?
2) Are the implementation using pass by reference and pass by pointer correct?
bool C::isSelf1(const C &c)
{
if (&c == this) {
return true;
} else {
return false;
}
}
bool C::isSelf2(C c)
{
if (&c == this) {
return true;
} else {
return false;
}
}
bool C::isSelf3(C * c)
{
if (c == this) {
return true;
} else {
return false;
}
}
int main ()
{
C c1 (2);
C * c2 = &c1;
cout << boolalpha;
cout << c2 -> isSelf1(c1) << endl; // pass by reference
cout << c2 -> isSelf2(c1) << endl; // pass by value
cout << c2 -> isSelf3(&c1) << endl;// pass by pointer
return 0;
}
There is a difference between:
and
So in 2nd version address of
Cobject (i.e.C*) is expected and not in 1st version.Also note that, internally 1st and 2nd versions might be implemented similarly; but there is a syntax difference. There is a 3rd version:
For edited question:
Not possible for your given requirement. Because it creates a new value and that would never match. Remove pass by value version from your code.
Apart from that, in general you should choose either pass by value or pass by reference, for any function. You can’t have both, because function call syntax for both of them would be same, which will result in ambiguity.
They are correct, but you can simplify them as:
Also, see the const correct-ness syntax of doing such things.