0

I know how how to use the virtual method to implement runtime polymorphism. But I can't understand why the method receiver must be pointer or reference.

From my thoughts, base class and derived class both has a pointer point to function table, When declare a non-pointer base class variable, it's easy to let that variable instance pointer member point to derived class virtual function table, like this:

class Base{
public:
    virtual void m1(){};
};

class Derived: public Base{
public:
    virtual void m2(){};
};

int main(){
    Base b = Derived(); // now b's hiding pointer point to Derived class virtual function table. 
}

This is just a language standard rule or some technically reasons? Thanks advance!

ideoutrea
  • 198
  • 1
  • 11
  • 1
    See: https://stackoverflow.com/questions/274626/what-is-object-slicing – Jeremy Friesner Sep 17 '22 at 04:35
  • Hey, the link is about object slicing, i don't think this is the same problem. C++ default copy constructor is member wise copy, Base and Derived class both has virtual function table pointer , why not the Derived class virtual function table pointer value can't copy to the Base class pointer? @JeremyFriesner – ideoutrea Sep 17 '22 at 04:52
  • 1
    In C++, an instance of a class (an object) is not a pointer. When you write `Base b`, you are declaring an instance of class `Base`, there are no pointers in this case. – heap underrun Sep 17 '22 at 04:55
  • 2
    @ideoutrea a vtable pointer has to point to the vtable of the class that it belongs to, so a `Base` object's vtable pointer must always point to the vtable for the `Base` class. Having it point to the vtable of a different class would cause misbehavior (e.g. if someone called `pointerToABaseObject->m1()`, `Derived::m2()` would execute instead, which would be incorrect since `Derived::m2()` expects to be called on a `Derived` object, not on a `Base` object) – Jeremy Friesner Sep 17 '22 at 05:04
  • Thanks, I got it, This is just a rule to to avoid some misbehavior to happens, right? @JeremyFriesner – ideoutrea Sep 17 '22 at 05:18
  • Right -- when possible, the compiler tries to prevent the programmer from doing things that are obviously incorrect, by issuing an error at compile-time. – Jeremy Friesner Sep 17 '22 at 05:23

0 Answers0