Calling private function by upcasting

41 views Asked by At

In the follwing class, I upcast a derived object to a base pointer. I'm then able to call the 'private' member function of derived from the main. How is this possible? My hunch is that whether a function can be called(i.e access) is based on the L-value(Base* b). What function is to be called is based on R-value(new Derived) as it is virtual. Can someone please clarify this for me?

#include <iostream>

class Base
{
  public :
  virtual void func1()
  {
    std::cout<<"Base func1";
  }
};

class Derived : public Base
{
  private :
  void func1()
  {
    std::cout<<"Derived Func1";
  }
};

int main()
{
  Base* b = new Derived;
  b->func1();
}

My output is

Derived func1
0

There are 0 answers