Skip to main content
4 of 4
added 195 characters in body
solti
  • 379
  • 2
  • 5
  • 10

How does the base class non-virtual function get called when derived class object is assigned to base class?

#include <iostream>

class Base {

private:
    int b_value;
public:
    void my_func() {std::cout << "This is Base's non-virutal my_func()" << std::endl; }

    virtual void my_Vfunc() {std::cout << "This is Base's virutal my_Vfunc()" << std::endl;}
};

  //----------------------------//


class Derived: public Base {

private:
    int d_value;
public:
    void my_func() {std::cout << "This is Derived's non-virtual my_func()" << std::endl; }

    virtual void my_Vfunc() {std::cout << "This is Derived's virtual my_Vfunc()" << std::endl;}
};


int main(){

Base * base = new Derived;
base->my_func();
base->my_Vfunc();
    
return 0; 
}

enter image description here

I was trying to understand the internal of virtual functions. So far I understand that upcasting the derived class to base class still calls the virtual function when we do base->my_Vfunc() because of Derived::vfptr.

My question is how does base's my_func() gets called here? My main confusion is how does (during the upcasting) the derived class object provide information about the base class non virtual function since it only has information of base as Base::b_value.

solti
  • 379
  • 2
  • 5
  • 10