I'm trying to learn C++ and ran into this confusing example in the tutorial I'm using perhaps someone can clarify this for me.
The following code is from the tutorial. I've put a "tag" (if you will // <---
)indicating the parts that are confusing to me.
#include <iostream>
using namespace std;
class CDummy {
public:
// signature: accepts an address
int isitme (CDummy& param);
};
// actual function that accepts an address passed in from main set to
// the param variable
int CDummy::isitme (CDummy& param) // <--- 1
{
Now here is where the confusing part comes. I'm taking the address of an address variable??? Wasn't the address already passed in?
if (¶m == this) return true; // <--- 2
else return false;
}
int main () {
CDummy a;
CDummy* b = &a;
// passes in the class
if ( b->isitme(a) )
cout << "yes, &a is b";
return 0;
}
Now below in the code that makes sense to me
#include <iostream>
using namespace std;
class CDummy {
public:
int isitme (CDummy *param);
};
int CDummy::isitme (CDummy *param) // <--- 1
{
this part makes perfect sense. param is a pointer and I'm comparing the pointer of class a with the pointer of class b.
if (param == this) return true; // <--- 2
else return false;
}
int main () {
CDummy a;
CDummy *b = &a;
// pass in the address.
if ( b->isitme(&a) )
cout << "yes, &a is b";
return 0;
}
Which one of the code samples is correct? Correct in the sense that this is the preferred way to do it, because they both work. Also, why am I taking an address of an address in the first example?
Apologies if this has been answered before but I couldn't find it. Thanks