dimanche 10 avril 2022

Why private virtual member function of a derived class is accessible from a base class

Consider the following snippet of code:

#include <iostream>
    
class Base
{
public:
  Base()
  {
      std::cout << "Base::constr" << std::endl;
      print();
  }
  virtual ~Base() = default;

  void print() const
  {
      printImpl();
  }
  
private:
    virtual void printImpl() const
    {
        std::cout << "Base::printImpl" << std::endl;
    }
};

class Derived : public Base
{
public:        
    Derived()
    {
        std::cout << "Derived::constr" << std::endl;
    }
    
private:
    void printImpl() const override
    {
        std::cout << "Derived::printImpl" << std::endl;
    }
};

int main()
{
    Base* ptr = new Derived();
    ptr->print();
    delete ptr;

    return 0;
}

The above code will print the following:

Base::constr

Base::printImpl

Derived::constr

Derived::printImpl

but I don't understand why printImpl private function is accessible from the base's print function. In my understanding this pointer implicitly passed to the print function holds the derived object's address, but I thought private member functions could be called ONLY from the member functions (and from friend functions) of the same class and here, Base class is not the same class as Derived, although there is an is a relationship.

Aucun commentaire:

Enregistrer un commentaire