0
votes

I'm a little bit confused concerning virtual functions.

Lets suppose you have Base class with virtual function foo(), and that function then overridden in Derived class

   class Baseclass
   {  
   public:
       virtual void foo()
       {
           //...
       }
   };

   class Derived: public BaseClass
   {
   private:
       int member_val;
   public:
       Derived( int init )
           : member_val( init )
       {}
       void foo()
       {
           member_val++;
       }
   };

and foo using member value of Derived class, when i write this code

Derived d( 10 );
Base* bPtr = &d;
bPtr->foo(); 

foo() called for Derived class because _vptr points on "Derived class virtual table", and pointer in "Derived class virtual table" points on foo() from Derived class, but how then it found member_val, cause Base pointer doesn't know about it. What "this" is passed to foo() from Derived class. We call it for Base* (this is Base type) but to find member_val we need Derived* ( this Derived type). So how it works under the hood?

1

1 Answers

0
votes

Right question is half an answer. Like in your case, you asked what this is passed to Derived::foo(), and the answer is "the same". You create an object of class Derived. It is allocatied in memory like the following:

Derived:
--------
vptr_t* vptr
int member_val

You then cast the &d, which is Derived* to Base*. What happened to the pointer? Nothing. It just changed its type, not the actual address it is pointing to. You can than convert it back to Derived* using dynamic_cast<Derived*>() or even static_cast<Derived*>. It is absolutely safe to use both in this case.

So the only actual question is how the table of virtual functions works? But this is another question, and it seems like you understand it.

Please note: things are more complicated with multiple inheritance, when several base classes are located in memory one after another.