C++ Virtual Functions – How Base Class Non-Virtual Function is Called

cvirtual-functions

#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.

Best Answer

Non-virtual functions are called based on the type that the compiler sees. If you have a Base* variable, then calling non-virtual functions will call the Base functions. That's the difference between virtual and non-virtual; calling a virtual function always calls the function that is appropriate for the object.

And you are not assigning an object. You are assigning an object pointer. If you assigned an object (for which you would have to implement an assignment operator), then both virtual and non-virtual would call the Base function, because the object would be a Base object.