When you define a derived class you can specify it’s relationship to the base class.
There are three options:
Example: Customer is a Person.
class Customer : public Person
class Customer : protected Person
class Customer : private Person
These three class access specifiers don’t affect how the derived class accesses members of the base class.
That access is purely based purely on the base class access modifiers.
The private access specifier changes all base class members to private in relation to external functions, including main(), which use objects of the derived class.
The specifier doesn’t affect access to its own members from external functions.
If you don’t use an access specifier when creating a derived class, the inheritance method is private by default.
A class’s private data can be accessed only by a class’s member functions, without appealing to friends.
Practically, the inheritance access specifier in derived classes is usually public.
class Base {
private:
int num;
public:
void setNum(int);
int getNum();
};
void Base::setNum(int n)
{
num = n;
}
int Base::getNum()
{
return num;
}
class Derived : private Base {
private:
int value;
public:
void setData(int n, int d);
int getValue();
int getNumber();
};
void Derived::setData(int n,int d)
{
setNum(n); // can be accessed
value = d;
}
int Derived::getValue()
{
return value;
}
int Derived::getNumber()
{
int nmbr=getNum(); // can be accessed
return nmbr;
int main()
{
Base bs;
// declare Base object
bs.setNum(4);
// OK. Public in Base
int nm = bs.getNum(); // OK. Public in Base
Derived dr;
// declare Derived object
dr.setData(10, 20);
// OK. Public in Derived
cout << "value=" << dr.getValue() << endl;
cout << "num=" << dr.getNum() << endl;
}
getNum() is a public member of Base . However, due to the private access specifier, it becomes a private member of Derived. We cannot call a private member function of the class from main().
One solution is to define a public function in the derived class to call the function defined in the base class.
This hides the base class function, and generally isn’t overloading because they aren’t visible in the same scope.
class Derived : private Base {
private:
int value;
public:
void setData(int, int);
int getValue();
int getNum();
};
int Derived :: getNum()
{
return Base :: getNum();
}
Another solution is to re-define the access privilege for the function in the derived class as public.
class Derived : private Base {
private:
int value;
public:
void setData(int, int);
int getValue();
using Base::getNum;
};
While possible, you should consider if the private inheritance specifier is really needed for your class hierarchy.