Reputation: 1862
struct A {
protected:
int y;
public:
int z;
};
struct F : A {
public:
using A::y;
private:
using A::z;
};
int main() {
F obj_F;
obj_F.y = 9;
obj_F.z = 10;
}
Source: http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/index.jsp?topic=/com.ibm.vacpp7a.doc/language/ref/clrc14cplr135.htm
In the above code obj_F.z = 10; - is allowed. Explanation: The access of member z is still public. The private using declaration using A::z has no effect on the access of z.
Can someone tell me, if z, which is declared as private, is accessible outside, then what is the meaning of that private? What does it do?
Thanks
-Saiyasodharan
Upvotes: 2
Views: 669
Reputation: 507273
The code is valid according to the Standard - see this Standard rule, which I did not have in mind when I answered before
A member m is accessible when named in class N if
- [...], or
- there exists a base class B of N that is accessible at the point of reference, and m is accessible when named in class B.
This entirely applies to your code, and thus the access is valid... It appears the main purpose of this rule is for allowing friend declarations of the base to apply to inherited members, but it also applies to this case.
(Disregard the parts of this that say the code is invalid - It's valid as explained above. This part is an old version of my answer, kept here to serve as background information)
No, this code is invalid. That's why the equivalent "access-declarations" are called that way (these are deprecated though)
struct F : A {
public:
A::y;
private:
A::z;
};
These are called "access-declarations" precisely because they can change the access... In your example the naming class is F
and z
as a member of F
is private because the using-declaration did change the access level of the name z
.
Upvotes: 3
Reputation: 5114
F inherits A privately. So you cannot access any of A's public members if you use an F outside F's definition. Because F defines no members, F is basically useless.
If F inherits A publicly (ie :)
struct F : public A {};
Then you can now use A's public member. so you can write obj_F.z
If you have a variable z that is public in a and private in F, ie :
struct A { public: int z; };
struct F : public A { private: int z; };
then the two z are actually two different variables. That's not what you want.
also, like Andre Holzner said, your using statement are useless here.
Generally, you cannot in any object programming language, restrict the scope of a member in a public-inherited subclass. Either the class definition won't compile, won't obey, or will create another member with the same name. This because your F is not compatible with code that deals with a A or a subclass of it.
Upvotes: -2