C++: overriding public\private inheritance

Jonathan picture Jonathan · Apr 22, 2011 · Viewed 10.7k times · Source

If B inherits from A using public, can B override one of the functions and force it to be private?

class A
{
public:
    virtual double my_func1(int i);
    virtual double my_func2(int i);
}

class B : public A // Notice the public inheritance
{
public:
    virtual double my_func1(int i);
private:
    virtual double my_func2(int i);
}

How about the other way around? if the inheritance type is private - can B force a specific function to be public?

What if A is pure abstract? does it make a difference?

Would protected make any difference in any combination?

Answer

Alok Save picture Alok Save · Apr 22, 2011

If B inherits from A using public, can B override one of the functions and force it to be private? NO

Eventhough the my_func1() is declared under priavte access specifier it can be still called through a pointer to class A, actually pointing to a object of class B

The call to my_func1() is evaluated at run time depending on the type of objected pointed by the pointer. At compile time the compile sees the my_func1() call as call to A::my_func1() and since A::my_func1() is public the compiler doesn't report only error. It is only at runtime that actual function call B::my_func1() is evaluated.

Ofcourse, You cannot directly call my_func1() through object of class B though because B::my_func1() is declared under Private Access specifier and You cannot access privately declared members from outside the class.

How about the other way around? if the inheritance type is private - can B force a specific function to be public?
NO

If you are calling my_func1() through a pointer of the Base class A, At compile time it is just evaluated as call to A::my_func1() which is Invalid since A::my_func1() is declared private inclass A`

What if A is pure abstract? does it make a difference?
NO
It makes no difference if the base class is Abstract or just polymorphic. Same rules will be applicable.

Would protected make any difference in any combination?
NO
As explained in first 2 Q's if you are calling a virtual function thorough pointer to Base class then at compile time the compiler only checks the access of that member function in Base class because compiler sees it as call to Base class member function. The actual call to the function is evaluated at run time and the feature is called Runtime Polymorphism or Dynamic polymorphism which is independent of the Access specifiers, which as a compile time construct.

So in conclusion,

overriding members of Base Class does not affect access