What is the value of private members here?
If I ha开发者_Go百科ve two classes A
and B
, such that B
inehrits A
. In other words, A
is the base class, and B
is the derived class.
Now, suppose that class A
has private
members. Since class B
inherited class A
, the private data members became part of class B
.
As we know, private members are said not to be accessed even by derived classes, but, they are now in the derived class. What is the value of privacy in this case?
Thanks.
They aren't usable in any way by member functions of B
, but they will be useful to member functions of A
, which B
in turn will rely on. It's simply another level of encapsulation (B
shouldn't care how the functionality of A
is implemented).
Well, since they are private to class A, I would assume instances of class A use them for something or other. If not, they can be removed.
The intention of "private" is to tell the developers who write the class B that they should not access this member.
The developer of class A uses the member a certain way that class B's developers do not need to concern themselves with.
The A members of the B objects will be whatever your object needs them to be in order to represent what you're representing with it. A class' methods probably uses them, and you'll probably call some A class methods. You should only care about A's public (or protected) interface, really, and make use of it.
e.g: if A is a TCP/IP protocol socket implementation which has write and read methods, B might be a SSL implementation on top of A. You'd (basically) redefine read and write so you do your encryption, and then use A::read and A::write to do your actual writing and reading from/to the socket. You have no need whatsoever to know what your socket (or the TCP protocol details) is in this design, so A abstracts it for you, and you have no access to it.
It will stay - a private member.
I don't know where you've seen that they are not to be accessed?
Because, believe it or not, you don't want to couple B to the implementation details of A. Imagine a scenario with the simplest kind of use:
struct A
{
protected:
int x;
};
struct B
{
void f() { ... access x and use as input ... }
};
Now, lets assume that a change to your product is required and now A doesn't have an x variable but instead fetches the value x meant to represent in some other way, composition maybe. Since B accesses the member directly you have to change any B that you've created to grab x through whatever new mechanism is not in place. The more you have to change the more room for problems there is.
If you'd instead made x a private member and provided a protected getter you'd not have this problem.
Again, this is the simplest example. In general values like x are used in the implementation of A's behavior and B should not be concerned with how the behavior is implemented nor should it have access to muck with it.
精彩评论