5
#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
  • 369
  • 2
  • 5
  • 10
  • 1
    Why? Because you didn't write `virtual my_Func` in the base class. That's what `virtual` means. Or are you really asking, "*How can the computer tell* what I wrote in the base class?" – Kilian Foth Feb 03 '16 at 08:25
  • Yes, I think I should ask how rather then why. – solti Feb 03 '16 at 08:28
  • I had hoped that this question was about slicing on assignment, but it seems that you've conflated pointers and objects. – Lars Viklund Feb 03 '16 at 08:38
  • hmm not assignment really ... I just wanted to know how internally the upcasting works. – solti Feb 03 '16 at 08:46

1 Answers1

7

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.

gnasher729
  • 42,090
  • 4
  • 59
  • 119