Hi,
I was following a book on C++ and came across the following:
According to the book this kind of code should work:
#include <iostream>
using namespace std;
struct sysop
{
int value;
};
const sysop & use(sysop & sysopref); // function with a reference return type
int main()
{
sysop tester =
{
0
};
sysop & n1 = use(tester);
cout << n1.value << endl;
return 0;
}
// use() return the reference passed to it
const sysop & use(sysop & sysopref)
{
sysop* psysop = new sysop;
sysopref.value++;
*psysop = sysopref; // copy info
return *psysop;
}
the book says that the function is returning a reference to structure sysop, so
the type of the variable n1 in main() should be reference to structure sysop.
however I get this compiler error:
"test.cpp", line 19: error: qualifiers dropped in binding reference of type
"sysop &" to initializer of type "const sysop"
sysop & n1 = use(tester);
^
1 error detected in the compilation of "test.cpp".
Therefore, i dropped the “&” in the assignment of n1, and then everything worked.
So now i wondered if it is a mistake in the book?
Strangely, they state that also the following code is correct:
#include <iostream>
using namespace std;
struct sysop
{
char name[26];
char quote[64];
int used;
};
const sysop & use(sysop & sysopref); // function with a reference return type
int main()
{
sysop looper =
{
"Rick \"Fortran\" Looper",
"I'm a goto kind of guy.",
0
};
use(looper); // looper is type sysop
cout << "Looper: " << looper.used << " use(s)\n";
sysop copycat;
copycat = use(looper);
cout << "Looper: " << looper.used << " use(s)\n";
cout << "Copycat: " << copycat.used << " use(s)\n";
cout << "use(looper): " << use(looper).used << " use(s)\n";
cout << "Copycat: " << copycat.used << " use(s)\n";
return 0;
}
// use() return the reference passed to it
const sysop & use(sysop & sysopref)
{
cout << sysopref.name << " says:\n";
cout << sysopref.quote << endl;
sysopref.used++;
return sysopref;
}
Here, according to my own view, a reference to structure sysop is returned
and assigne to a structure sysop, not a reference to structure sysop.
The only difference being the fact that no pointers are used.
Also, in the first program, I wonder what kind of delete statement I should use?
I thought this would be correct:
delete &n1
but I don’t know how to be sure.
Thanks for any insight on the intricacies of this reference stuff.
Steven