Control Variable and Virtual Functions

I found strange behavior when using a reference variable.

Here is the implementation of the classes:

class Base { public: virtual void Method() = 0; }; class DerivedA : public Base { public: virtual void Method() {} } class DerivedB : public Base { public: virtual void Method() {} } 

Here is an example of code that has weird behavior:

 void main(int argc, char *argv[]) { DerivedA a; DerivedB b; Base &base = a; base.Method(); // Calls DerivedA::Method base = b; base.Method(); // Calls DerivedA::Method!!! Why doesn't call DerivedB.Method()? } 

In conclusion, it seems that the virtual table pointer function is β€œlinked” to the reference variable only when initializing reference variables. If I reassign the reference variable, vfpt will not change.

What's going on here?

+6
source share
2 answers

Base &base is a reference, that is, an alias of the object a , so assigning base = b equivalent to a = b , which leaves the base object still the same object in the same class. This is not a reassignment of the pointer, as you assume.

+13
source

Links can only be initialized once. You cannot assign a new object to a link. What actually happens here is that operator = from Base is called, and the base object is still DerivedA, not DerivedB.

+7
source

Source: https://habr.com/ru/post/902992/


All Articles