2

I am able to invoke the private function of the derived class. Is this Ok?

#include <iostream>
class A {
public:
    virtual ~A() {}

    virtual void func()
    {
        std::cout << " Printing from A" << std::endl;
    }
};

class B : public A {
private:
    virtual void func()
    {
        std::cout<< " Printing from B"<<std::endl;
    }
};

main()
{
    B b;
    A* a = &b;

    a->func();
    // b.func(); Not possible as expected.
}

Below is the output

Printing from B

Jarod42
  • 203,559
  • 14
  • 181
  • 302

2 Answers2

7

Access to a virtual function is determined by its declaration in the static type of the object, and not by the declaration of the overriding function in the dynamic type.

§11.5 [class.access.virt] The access rules (Clause 11) for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it.

Access is checked at the call point using the type of the expression used to denote the object for which the member function is called. The access of the member function in the class in which it was defined is in general not known.

Since A::func is public, calling B::func polymorphically through a pointer to A is fine.

Community
  • 1
  • 1
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
6

Access specifiers are checked at the level of the static type of the object, pointer or reference on which the call is made even if the call is dispatched to the dynamic type of the object pointed/referenced. In your case, a->func() is called through a pointer of type A*, and thus access specifiers are checked at the A level, where func() is public.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489