Reputation: 7873
I realize that the following is horrible style, but for the sake of argument, assume I have the following code:
struct parent
{
virtual ~parent() {}
};
struct child : public parent
{
child() {}
virtual ~child() {}
};
struct anotherClass
{
static parent& anyName;
};
child anyName; // create an instance of 'child'
parent& anotherClass::anyName = anyName; // create a parent-class ref to the child object
When I initialize the anotherClass::anyName
reference above with anyName
, which anyName
am I initializing it with? The child-class object, or with itself? (To which entity does the last anyName
in the last line refer? Is it ambiguous?) And where in the C++ spec would something like this be addressed?
(BTW this question has absolutely nothing to do with my other question posted a few minutes earlier.)
Upvotes: 3
Views: 121
Reputation: 283624
With itself.
Unlike your other question, this one can be solved through a bit of sample code. I plugged the code from your question into an online compiler (clang) ...
The compiler's response is pretty clear:
warning: reference 'anyName' is not yet bound to a value when used within its own initialization
(Try commenting-out your child anyName;
line; note that the compilation result doesn't change, because the compiler wasn't finding that object anyway.)
The rules from the C++ Standard that apply are in [basic.lookup.unqual]
:
A name used in the definition of a static data member of class
X
(after the qualified-id of the static member) is looked up as if the name was used in a member function ofX
.
and from [basic.scope.pdecl]
The point of declaration for a name is immediately after its complete declarator and before its initializer (if any), except as noted below.
These two rules together ensure that the initializer's unqualified lookup of anyName
finds anotherClass::anyName
.
Upvotes: 5