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;
}