On Dec 31, 5:45 am, "Jim Langston" <tazmas...@rocketmail.com> wrote:
fl wrote:
There is a question about nonstatic member. C++ primer says:
A nonstatic member is restricted to being declared as a
pointer or reference to an object of its class. It only
gives an example of pointer *b.
class Bar {
public:
private:
static Bar a; // OK
Bar *b; // OK
Bar c; // error
My question is how a nonstatic member is declared as a
reference to an object of its class. Because a reference is
legal only after the original variable has been declared,
where is the original object? I feel it is really bizarre.
Could you give me an example? Thanks in advance.
Passing it as a parameter to the constructor is one way. this
(the instance pointer) is another. In fact, class member
references have to be initialized in the constructor
initialization list (I know of no other way) and passing as a
paramter would be the usuall way. Something like (untested
code)
class Bar {
public:
Bar( Bar& foo ): d( foo ) {}
private:
Bar& d;
};
Note that if that's the only constructor, there's no way to
create an instance of the class, because in order to create an
instance, you have to have an instance. (Note too that your
constructor is a copy constructor. I'm not sure if this is
intentional or not---it doesn't have the classical copy
semantics, but on the other hand, I can't imagine any other
reasonable approach if you don't want to have to test for null
pointers, etc.)
About the only case I can imagine where a reference to the class
itself would make sense if if you provide a default constructor
which initializes it to *this. Given the usual way people
understand things, I rather suspect that in such cases, most of
the time, using pointers would result in more understandable
code. But that may just be me.
Yes, you are right. Although this compiles:
would cause problems as you can't reseat a reference. It could be done, but
probably shouldn't.