If a base class is publicly inherited ,member functions of derived class(inherited member functions from base class or member function of derived class) can access the private member of base class or not?
If you have a class that's publicly inherited from a base class
-public members of base class will become public members of the derived class
-protected members of base class will become protected members of the derived class
-private members of the base class will become inaccessible to the derived class
class BaseClass
{
private:
int number;
public:
BaseClass();
~BaseClass();
void setNumber(int);
int returnNumber();
}
If you create an object of BaseClass BaseClass baseObject; You can only access number via the two public functions setNumber(int) and returnNumber() since number is private.
There is therefore no way for you to access number that way: baseObject.number
It is therefore inaccessible
So if you have a derived class from BaseClass
1 2 3 4
class DerivedClass : public BaseClass
{
//...
}
You will neither be able to access number directly like so:
class DerivedClass : private BaseClass
{
public:
void attemptSetNumber(int);
};
void DerivedClass::attemptSetNumber(int n)
{
setNumber( n ); // OK: call public base member
}
int main()
{
BaseClass baseObject;
baseObject.setNumber(5); // OK: public member
DerivedClass derivedObject;
derivedObject.attemptSetNumber(10); // OK: public member
baseObject.setNumber(5); // ERROR: 'BaseClass' is not an accessible base of 'DerivedClass'
BaseClass& R = derivedObject; // ERROR: 'BaseClass' is an inaccessible base of 'DerivedClass'
R.setNumber(20); // would be ok, if you could have R.
return 0;
}
The DerivedClass inherits from BaseClass, and therefore it can access the public (and protected) members of the BaseClass.
The inheritance is private, and therefore all BaseClass members of the DerivedClass are private for outsiders.