Reputation:
I want to have members inherited private. I think I saw an example of making them public nevertheless this fact that are derived with private keyword. My question: how to do it, and if it is possible then shouldn't it be prohibited?
class U{
public:
int a;
protected:
int b;
private:
int c;
};
class V : private U{
public:
int i;
//can make a public again?
};
Upvotes: 6
Views: 1042
Reputation: 29724
how to do it?
perfectly possible, use the using
keyword.
shouldn't it be prohibited?
No need. You can always return members back their accessibility but not more than it was initially. So, if the base class initially has declared something as public and it was just your idea/restriction to make it private, this doesn't hurt base class if you drop this restriction and leave this as public, all in all it was public at the beginning. Cite from "C++ Programming Language" will help best here.
A using-declaration cannot be used to gain access to additional information. It is simply a mecha- nism for making accessible information more convenient to use.
so if it was accessible in base class, and you derived your class with protected
or private
keyword you can remove this restriction and return them back their initial level of access by "transporting" them to appropriate part (public,protected,private
) in your derived class definition.
class U{
public:
int a;
protected:
int b;
private:
int c;
};
class V : private U{
public:
using U::b;
using U::a;
};
int main(int argc, char** argv) {
V v;
printf("\nV: %d %d %d",v.a,v.a,v.b);
U u;
printf("\nU: %d %d %d",u.a,u.a,u.a);
return 0;
}
Upvotes: 5
Reputation: 227370
You cannot make U::c
public, because it is private
to U
, so it cannot be accessed from V
. If it were public
or protected
, then you could, with a using
declaration. Therefore, you can make U::a
and U::b
public, but not U::c
:
class V : private U{
public:
int i;
//can make c public again?
using U::c; // ERROR: only if U::c is public or protected in U
using U::a; // OK
using U::b; // OK
};
Upvotes: 3
Reputation: 126412
You cannot make c
public because it is private to U
and not accessible from V
(besides, a design that would require that is probably flawed, as it would violate encapsulation - a class should not know/care about private
members of other classes).
However, the same is not true of protected
and public
members, whose access level can be overridden by derived classes through a using
declaration. For instance:
class V : private U{
public:
int i;
using U::a;
// ^^^^^^^^^^^ Gives "a" public accessibility
using U::b;
// ^^^^^^^^^^^ Gives "b" public accessibility
// using U::c; // ERROR! c is not accessible from V
};
The above would make b
accessible from client code external to V
and U
:
int main()
{
V v;
v.a = 42; // OK
v.b = 1729; // OK
}
Upvotes: 6