Here is a test question:
Consider the following code:
class A { typedef int I; // private member I f(); friend I g(I); static I x; };
Which of the following are valid:
a. A::I A::f() { return 0; } b. A::I g(A::I p = A::x); c. A::I g(A::I p) { return 0; } d. A::I A::x = 0;
Answer to this question is considered correct only the first version (a.), but why? All them are valid in my opinion. Even tested all they compile successfully. Why only the first answer is correct?
Whoever wrote the original answer to the test is wrong.
The example goes even further in the standard, with templates (I'll omit them here):
class A { typedef int I; // private member I f(); friend I g(I); static I x; }; A::I A::f() { return 0; } A::I g(A::I p = A::x); A::I g(A::I p) { return 0; } A::I A::x = 0;
Here, all the uses of
A::I
are well-formed becauseA::f
andA::x
are members of class A and g is a friend of class A. This implies, for example, that access checking on the first use ofA::I
must be deferred until it is determined that this use ofA::I
is as the return type of a member of class A. ]
They are all valid C++.
Here is the exact code, it is an example from the standard itself:
http://www.open-std.org/jtc1/sc22/open/n2356/access.html
This is how I parse them:
a. A::I A::f() { return 0; } // defines A::f() which was previously prototyped b. A::I g(A::I p = A::x); // declares prototype g(A::I), but doesn't define it c. A::I g(A::I p) { return 0; } // defines g(A::I) d. A::I A::x = 0; // defines static storage for A::x which was previously declared in A
These all compile, both individually, and collectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With