patrick@cos.com (Patrick Steranka) (12/03/89)
In BS, pg 164, 5.5.6 it states:
The assignment to "this" [in a constructor function] informs
the compiler that the programmer has taken control and that the
default mechanism for allocating storage should not be used.
With this in mind my questions are:
(1) Does the variable 'this' have to be set in the constructor
function or can it be set in a subroutine that is called from
a constructor?
(2) If a member function (called from within the constructor) sets
the value of 'this', does the compiler still understand that
"the programmer has taken control"?
(3) Can a "friend" function access (get or set) the value of 'this'?
After testing several examples I learned the answers to questions
1 and 2:
(1) Only a constructor can set the value 'this'.
(2) If a member method attempts to change the value of 'this', an
error occures which says something to the effect of:
'You can't modify read-only variable $this'
But the answer to question #3, is not clear. Although I know
(intuitively) the answer must be that non-member functions can't
access 'this'. The error message that I got didn't make it
clear to me.
To answer question #3, I tried the following example.
==================== OUTPUT from compiling ex7.cc ====================
g++ -o ex7 -g ex7.cc
ex7.cc: In function void def_this ():
ex7.cc:15: request for `this' not in a class, struct, or union
==================== OUTPUT from compiling ex7.cc ====================
Perhaps the error message:
"Illegal attempt to use 'this' in a non-member function"
would be more correct, or am I missing something?
This error was produced on a SUN 3/280 (running SUN OS 3.5)
using g++ (1.36.1).
============================== File: ex7.cc ==============================
#include <stream.h>
class T{
char s[500];
friend void def_this();
public:
T() {
def_this(); cout << "The value of 'this' is " << (int)this << "\n";
};
~T() {
cout << "In ~T, the value of 'this' is " << (int)this << "\n";
this = 0;
}
};
void def_this() { this = (T *) 0x43; }
main(int argc, char* argv[])
{
T a1;
}
============================== File: ex7.cc ==============================
patrick (Patrick Steranka @ Corporation for Open Systems)
-- patrick@cos.com
-- patrick%cos.com@uunet.uu.net
-- {uunet, sundc, decuac, hqda-ai, hadron}!cos!patrick
P.S. If this kind of a report is too "nit-picky", then tell
me to stop sending them and I will.