Possible Duplicate:
What are access specifiers? Should I inherit with private, protected or public?
How can I create a derived class in C++ which preserves the properties and methods’ access specifier like this:
class Base
{
private:
void base_private();
protected:
void base_protected();
public:
void base_public();
};
class A: [what type is appropriate here?] Base
{
public:
void test() {
base_protected(); // Ok
}
};
class B: [what type is appropriate here?] A
{
public:
void test() {
base_protected(); // Ok
}
};
int main()
{
A a;
B b;
a.base_public(); // Ok
a.base_protected(); // Not Ok
b.base_protected(); // Not Ok
b.test(); // Ok
return 0;
}
I mean base_protected() method is still protected in derived classes but base_public() is public.
Lets consider the availability of members of
Base:base_privateis not available to clients but available toBaseitselfbase_protectedis not available to clients but available toBaseitselfbase_publicis available to both clients andBaseNow, if you have
class A : public Base(public inheritance), the availability of the members ofBasewill be:base_privateis not available to clients and not available toAitselfbase_protectedis not available to clients but available toAitselfbase_publicis available to both clients andANow, what you’re asking about is how to keep the same client interface for both classes,
BaseandA. If you look at the availability of the members for clients in the lists above, you will see that it is precisely the same forBaseandA:base_privateis not available;base_protectedis not available; andbase_publicis available.The only thing that has changed between
BaseandAis thatAcannot access the members that are private toBase. That’s the whole point of theprotectedaccess control – it gives derived classes access to their base classes members without making them available to clients.So
publicinheritance is what you need.